首页 > input如何根据文本自适应宽度

input如何根据文本自适应宽度

<input class="form-control" type="text" placeholder="input如何根据文本自适应长度" />


有一部分的input或者textarea宽度自适应是使用div加上contenteditable属性实现,当然内容你需要做一定限制,不然标签什么都可以写进去,富文本编辑器就是用这个实现的


<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script>
function demo() {
var testLength = document.getElementById('test').value.length
$("#test").css('width', testLength*5 + 'px')
}
</script>
<body>
<input id="test" onkeypress="demo()" type="text"/>
</body>
</html>

使用纯粹的css没办法做到完整的自适应,你可以使用Js来实现这个功能,给input监听keypress事件,依据input的内容length,来动态更改input的width

【热门文章】
【热门文章】