CSS实现动态生成textarea加载时高度自适应内容无滚动条
问题原因
height: fit-content 仅对普通块级容器生效,<textarea> 属于表单替换元素,无法识别该属性,默认会按照内置的2行高度渲染,不会随内容自动撑开,即使设置了overflow: hidden也不会自动适配内容高度。
修复方案
需要同时调整CSS和补充少量JS逻辑,实现textarea高度完全贴合内容:
- 调整CSS样式:给textarea补充
box-sizing: border-box,移除无效的height: fit-content声明,避免高度计算偏差 - 补充JS高度计算逻辑:每次动态插入textarea后,先重置高度为auto,再将元素的
scrollHeight设为实际高度,就能让高度刚好容纳所有内容,不出现滚动条。如果需要支持用户输入内容时自动调整高度,额外绑定input事件触发同样的高度计算逻辑即可。
补充:如果不需要兼容2024年以前的旧版浏览器,可以直接给textarea设置
field-sizing: content;属性,无需JS即可实现内容自适应高度,但该属性兼容性较差,生产环境不推荐优先使用。
修改后的完整代码
CSS部分
.flow-div { position: absolute; top: 0; left: 0; height: 100%; width: 33.33%; background: whitesmoke; opacity: 1; } .wrapper { position: relative; margin: 20px; height: fit-content; background: white; border-radius: 10px; box-shadow: -10px -10px 10px rgba(255, 255, 255, 0.5), 15px 15px 15px rgba(70, 70, 70, 0.12); padding: 10px; overflow-y: auto; } .notes-container { position: relative; margin: 20px; height: fit-content; } .notes-textfield { position: relative; border-radius: 10px; padding: 10px 10px 0 10px; border: none; resize: none; overflow: hidden; box-sizing: border-box; border-bottom: 2px solid rgb(0, 50, 115, 0.25); width: calc(100% - 20px); } #flow-desc { }
JS部分
const data = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ips um has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." // textarea高度自适应逻辑 function adjustTextareaHeight(textarea) { textarea.style.height = 'auto'; textarea.style.height = `${textarea.scrollHeight}px`; } $("#flow-desc").html("") for (let i = 0; i < 4; i++) { const $textarea = $(`<textarea class="notes-textfield col-10" placeholder="#Notiz">${data}</textarea>`); const $container = $(`<div class="notes-container" id="${i}"></div>`).append($textarea); $("#flow-desc").append($container); // DOM插入完成后计算高度 adjustTextareaHeight($textarea[0]); // 可选:监听用户输入,实时调整高度 $textarea.on('input', function() { adjustTextareaHeight(this); }) }
HTML部分(无需调整)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div class="flow-div"> <div class="wrapper"> <div id="flow-desc"> <!-- 内容由脚本动态填充 --> </div> </div> </div>
注意:高度计算逻辑必须在textarea插入到DOM树之后执行,元素未渲染完成时获取的
scrollHeight数值不准确,会导致高度计算错误。
内容的提问来源于stack exchange,提问作者ICoded
相关产品推荐
相关产品推荐

