我创建此代码是为了当内部文本超过文本区域的高度时自动扩展文本区域的高度,但这仅在 jsfiddle 中有效,但当我在项目中运行此代码时,这不起作用。有人可以帮助我吗?谢谢。
$("#ta").keyup(function (e) {
autoheight(this);
});
function autoheight(a) {
if (!$(a).prop('scrollTop')) {
do {
var b = $(a).prop('scrollHeight');
var h = $(a).height();
$(a).height(h - 5);
}
while (b && (b != $(a).prop('scrollHeight')));
};
$(a).height($(a).prop('scrollHeight') + 20);
}
autoheight($("#ta"));
#ta {
width:250px;
min-height:116px;
max-height:300px;
resize:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="ta"></textarea>
最佳答案
如果您使用jquery,那么您必须加载Jquery 库并将代码添加到准备好的文档或窗口加载中。以下是更新后的代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
#ta {
width:250px;
min-height:116px;
max-height:300px;
resize:none;
}
</style>
<script>
$(document).ready(function(){
$("#ta").keyup(function (e) {
autoheight(this);
console.log("log");
});
});
function autoheight(a) {
if (!$(a).prop('scrollTop')) {
do {
var b = $(a).prop('scrollHeight');
var h = $(a).height();
$(a).height(h - 5);
}
while (b && (b != $(a).prop('scrollHeight')));
};
$(a).height($(a).prop('scrollHeight') + 20);
}
autoheight($("#ta"));
</script>
</head>
<body>
<textarea id="ta"></textarea>
</body>
</html>
关于javascript - 扩大文本区域高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41845294/