如何获取带rows属性的textarea文本高度?scrollHeight失效问题
获取带固定rows属性的textarea文本实际高度
直接操作原元素移除rows属性会导致Safari页面跳动,推荐使用克隆隐藏textarea的方法,完全不影响原元素布局:
- 创建一个与目标textarea样式一致的隐藏副本
- 复制目标textarea的内容到副本
- 读取副本的scrollHeight(副本无rows限制,能正确反映文本高度)
实现代码
function getTextareaContentHeight(targetTextarea) { // 创建textarea副本 const cloneTextarea = document.createElement('textarea'); // 复制影响文本渲染的关键样式 const computedStyles = window.getComputedStyle(targetTextarea); cloneTextarea.style.fontFamily = computedStyles.fontFamily; cloneTextarea.style.fontSize = computedStyles.fontSize; cloneTextarea.style.fontWeight = computedStyles.fontWeight; cloneTextarea.style.lineHeight = computedStyles.lineHeight; cloneTextarea.style.padding = computedStyles.padding; cloneTextarea.style.borderWidth = computedStyles.borderWidth; cloneTextarea.style.width = computedStyles.width; cloneTextarea.style.resize = 'none'; // 隐藏副本,避免干扰页面布局 cloneTextarea.style.position = 'absolute'; cloneTextarea.style.top = '-9999px'; cloneTextarea.style.left = '-9999px'; // 复制目标textarea的内容 cloneTextarea.value = targetTextarea.value; // 插入到DOM中才能正确计算高度 document.body.appendChild(cloneTextarea); const contentHeight = cloneTextarea.scrollHeight; // 用完后移除副本,清理DOM document.body.removeChild(cloneTextarea); return contentHeight; } // 使用示例 const textarea = document.querySelector('textarea'); console.log(getTextareaContentHeight(textarea));
原理说明
这个方法通过克隆元素计算高度,完全不会修改原textarea的任何属性或样式,因此不会触发Safari的布局跳动问题。复制的样式确保了副本的文本渲染逻辑和原元素完全一致,获取的scrollHeight就是文本的实际高度。
内容的提问来源于stack exchange,提问作者Ood
相关产品推荐
相关产品推荐

