You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

浏览器窗口resize时如何实现textarea高度自动适配内容

核心问题排查

你的代码存在两处逻辑错误导致无法运行:

  1. 事件绑定逻辑错误:window.addEventListener("resize", autoResize(tx[i])) 写法会在页面加载时立即执行autoResize函数,把函数返回的undefined绑定给resize事件,窗口调整时不会触发对应逻辑。
  2. this指向错误:autoResize函数内使用this.scrollHeight取高度,此时this指向全局window对象,无法拿到textarea的实际内容高度。

修复后可运行代码

var tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  // 初始化隐藏滚动条
  tx[i].style.overflowY = "hidden";
  // 页面加载时先初始化textarea高度
  autoResize(tx[i]);
  // 绑定窗口resize事件,用箭头函数包裹避免立即执行
  window.addEventListener("resize", () => autoResize(tx[i]));
  // 可选配置:如果需要同时支持用户输入时自动调整高度,加下方这行
  // tx[i].addEventListener("input", () => autoResize(tx[i]));
}

function autoResize(el) {
  // 先重置高度为auto,才能计算到当前宽度下内容的实际总高度
  el.style.height = "auto";
  // 直接用传入的textarea元素取scrollHeight
  el.style.height = el.scrollHeight + "px";
}

性能优化版本(可选)

窗口resize事件触发频率极高,频繁调整高度会产生不必要的性能开销,可以加防抖逻辑限制触发频率:

var tx = document.getElementsByTagName("textarea");
// 防抖函数:300ms内多次触发只执行最后一次
function debounce(func, delay = 300) {
  let timerId;
  return function(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => func.apply(this, args), delay);
  }
}
const debouncedAutoResize = debounce(el => autoResize(el));

for (let i = 0; i < tx.length; i++) {
  tx[i].style.overflowY = "hidden";
  autoResize(tx[i]);
  window.addEventListener("resize", () => debouncedAutoResize(tx[i]));
}

function autoResize(el) {
  el.style.height = "auto";
  el.style.height = el.scrollHeight + "px";
}

内容的提问来源于stack exchange,提问作者irisnviolets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:06:04