txtaAutoHeight方法是一个很好用的jquery的一个可以使textarea自适应高度的方法。
用法如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自适应高度</title>
<link rel="stylesheet" href="css/layui.css">
<style>
body{
display: flex;
justify-content: center;
}
.div1{
width: 300px;
height: 50px;
margin: 10px auto;
border: 1px solid #000;
padding: 10px;
}
</style>
</head>
<body>
<textarea class="div1">
</textarea>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$.fn.extend({
txtaAutoHeight: function () {
return this.each(function () {
var $this = $(this);
if (!$this.attr('initAttrH')) {
$this.attr('initAttrH', $this.outerHeight());
}
setAutoHeight(this).on('input', function () {
setAutoHeight(this);
});
});
function setAutoHeight(elem) {
var $obj = $(elem);
return $obj.css({ height: $obj.attr('initAttrH'), 'overflow-y': 'hidden' }).height(elem.scrollHeight);
}
}
});
$(function () {
$(".div1").txtaAutoHeight();
});
</script>
</body>
</html>
引入该方法之后,然后初始化,就能够使textarea可以自适应高度。
——————————————————————————————————————
但是在某些时候,这个方法有时候会无法正常使用,例如删减数字的时候会接着增加textarea的高度,经检查发现textarea的元素中用到了layuiUI框架中的layui-textarea的元素类,例如:
<textarea class="div1 layui-textarea"></textarea>
当使用了ui插件时候txtaAutoHeight方法运行不正常,在去引入的css文件中搜索textarea这个名称,发现了在.layui-textarea:{outline: none; -webkit-appearance: none; transition: all .3s; -webkit-transition: all .3s; box-sizing: border-box;}
中的transition: all .3s; -webkit-transition: all .3s;
是问题所在,去除掉这两个属性之后txtaAutoHeight方法可以在textarea中正常使用,所以在使用txtaAutoHeight这个方法时textarea中不可以设置transtion这个属性,否则方法就不能正常运行。