javascript - 扩大文本区域高度

标签 javascript jquery html jsfiddle

我创建此代码是为了当内部文本超过文本区域的高度时自动扩展文本区域的高度,但这仅在 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/

相关文章:

javascript - 如何删除已知 ID 元素中的特定子元素?

javascript - 使用 jQuery 在重复部分内重复字段

javascript - 最大距离光线转换

jquery - 使用 jQuery 显示/隐藏内容

Javascript:使用按钮保存 .innerHTML 数据

html - 如何从网页链接到微信?

javascript - CamanJS 在 Canvas 上用图像初始化(RETINA BUG)

javascript - 在这个 switch 语句中执行 `return ' ' ;` or ` return null;` 是否更有意义?

javascript - 多个元素的相同点击事件,具体情况

css - 用覆盖 mask div,防止 mask 滚动