您的位置:首页 > Web前端 > JavaScript

js根据输入字符长度自动调整textarea高度

2018-03-07 11:24 441 查看

1.编写html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动扩展文本框高度</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#words").on("input propertychange",function(e){
var target = e.target;
var dh = $(target).attr('defaultHeight') || 0;
if (!dh) {
dh = target.clientHeight;
$(target).attr('defaultHeight', dh);
}

target.style.height = dh + 'px';
var clientHeight = target.clientHeight;
var scrollHeight = target.scrollHeight;
if (clientHeight !== scrollHeight) {
target.style.height = scrollHeight + 10 + "px";
}
});
});

</script>
</head>
<body style="text-align: center">
<label><h3>请输入:</h3></label><br>
<textarea id="words" name="words" style="width: 300px;height: 30px;" default-height="20px"></textarea>
</body>
</html>

2.调试

2.1绑定函数前效果



2.2绑定函数后效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: