请返回 jstextarea 自适应高度
以下是一个简单的实现:
function autoHeight(elem) {
elem.style.height = "auto";
elem.style.height = elem.scrollHeight + "px";
}
// 使用示例
const textarea = document.querySelector("textarea");
autoHeight(textarea);
该函数接受一个 textarea 元素作为参数,将其高度设置为 auto,然后再将其高度设置为 scrollHeight,即 textarea 内容的完整高度。这样,当 textarea 内容变化时,其高度也会相应地自适应变化。
你可以将该函数绑定到 textarea 的 input 或 change 事件上,以在内容变化时自动调用。例如:
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", () => {
autoHeight(textarea);
});
原文地址: http://www.cveoy.top/t/topic/GD3 著作权归作者所有。请勿转载和采集!