首页 > 解决方案 > Textarea scrollHeight 不更新防止自动调整大小

问题描述

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

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

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

如果我单击文本区域,它会调整大小。如果我从文本区域输入或删除文本,它会调整大小。

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

调整大小函数如下。

$(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";
    }
});

标签: javascripttextareaautoresize

解决方案


一个快速而肮脏的解决方案是强制代码等到第一次打开模式后再添加“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";
    }
});

推荐阅读