可以通过以下代码实现:

// 获取 textarea 元素
const textarea = document.querySelector('textarea');

// 设置 textarea 的初始高度
textarea.style.height = 'auto';

// 监听 textarea 的输入事件
textarea.addEventListener('input', () => {
  // 设置 textarea 的高度为 auto,以便获取实际内容高度
  textarea.style.height = 'auto';
  // 获取实际内容高度
  const height = textarea.scrollHeight;
  // 设置 textarea 的高度为实际内容高度
  textarea.style.height = `${height}px`;
});

这样,当你通过 JavaScript 改变 textarea 的 value 值时,输入事件会被触发,自适应高度也会随之改变。

通过 js 改变 textarea value 时触发自适应高度

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

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