为了实现 textarea 的高度自适应内容,可以使用以下方法:

1.使用 JavaScript 监听 textarea 的输入事件,每次输入时重新计算 textarea 的高度,并设置其高度为计算出的值。

function autoResizeTextarea(element) {
  element.style.height = "auto";
  element.style.height = element.scrollHeight + "px";
}

const textarea = document.getElementById("myTextarea");
textarea.addEventListener("input", function() {
  autoResizeTextarea(this);
});
  1. 使用 CSS 样式设置 textarea 的高度为 auto,并设置其最小和最大高度,这样当内容超出最大高度时会出现滚动条。
textarea {
  height: auto;
  min-height: 100px;
  max-height: 200px;
  overflow-y: auto;
}

综合以上两种方法,可以实现 textarea 的高度自适应内容。

textarea 的高度自适应内容

原文地址: http://www.cveoy.top/t/topic/GFW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录