javascript - 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";
}
});
解决方案
一个快速而肮脏的解决方案是强制代码等到第一次打开模式后再添加“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";
}
});
推荐阅读
- git - 如何在现有分支之上合并新的 git 提交历史列表?
- c# - 如何拥有一系列 Windows 服务
- php - MongoDB 结构,用于消息传递具有完整功能的项目部分(专门从一个用户删除)
- c# - 统一构建/放置对象系统
- c# - Unity C# Firebase:如果“task.Exception.Message”返回“发生了一个或多个错误”并且没有返回数据,我该怎么办?
- mysql - mysql从完整路径查询父路径
- jquery - 如何使光滑的滑块和光滑的灯箱与 woocommerce 中的产品画廊一起正常工作
- javascript - 确认弹出框后如何重置选择选项
- python - 在 Gensim 中训练分布式 LdaModel 时出现 AssertionError
- javascript - 根据地图函数中的条件显示不同的标签或项目