【问题标题】:Textarea scrollHeight not updating preventing auto resizeTextarea scrollHeight 不更新防止自动调整大小
【发布时间】:2020-04-29 18:32:45
【问题描述】:

我有点卡在看似简单但行不通的事情上。

我想在模式中创建一个自动调整大小的文本区域。 textarea 的值根据激活模态的元素添加到模态显示中。

在模态外观上,文本区域未调整大小,控制台将 0 报告为 scrollHeight。

如果我点击文本区域,它会调整大小。 如果我在 textarea 中输入或删除文本,则会调整其大小。

当以编程方式设置值时,我无法弄清楚为什么它会报告 scrollHeight 0。

resize函数如下。

$(document).on("input change focus", "textarea.notesarea", function (e) {
    this.style.height = 'auto';
    console.log(this.scrollHeight+ "-"+ $(this)[0].scrollHeight); 
    if (this.scrollHeight == 0) {
        this.style.height = "calc(2.25rem + 2px)";
    } else {
        this.style.height = 0;
        this.style.height = (this.scrollHeight + 4) + "px";
    }
});

【问题讨论】:

    标签: javascript textarea autoresize


    【解决方案1】:

    一个快速而肮脏的解决方案是强制代码等到第一次打开模式后再添加“calc(2.25rem + 2px)”;到它的高度。 您可以使用 setTimeout(function(){... 例如:

    $(document).on("input change focus", "textarea.notesarea", function (e) {
        this.style.height = 'auto';
        console.log(this.scrollHeight+ "-"+ $(this)[0].scrollHeight); 
        if (this.scrollHeight == 0) {
            that = this;
            setTimeout(function(){
              that.style.height = "calc(2.25rem + 2px)";
            },300);
        } else {
            this.style.height = 0;
            this.style.height = (this.scrollHeight + 4) + "px";
        }
    });
    

    【讨论】:

    • 我使用这种方法进行了一些修改。我将超时设置为 0,在超时内我使用了 "this.style.height = (this.scrollHeight + 4) + "px";"
    猜你喜欢
    • 2014-09-04
    • 2012-11-16
    • 2021-11-25
    • 1970-01-01
    • 2013-06-21
    • 2019-06-27
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多