跳到主要内容

操作

2023年11月08日
柏拉文
越努力,越幸运

一、textarea 高度自适应


<textarea style="height: 36px; resize: none; line-height: 20px; box-sizing: border-box;"></textarea>
<script>
const textarea = document.querySelector('textarea')
textarea.oninput = function (e) {
const style = getComputedStyle(e.target);
let height = parseInt(style.height.slice(0, -2), 10);
const lineHeight = parseInt(style.lineHeight.slice(0, -2), 10);

if (e.target.scrollHeight > height) {
e.target.style.height = `${e.target.scrollHeight + 2}px`
} else {
while (height >= e.target.scrollHeight) {
e.target.style.height = `${height - lineHeight}px`
height -= lineHeight
}
e.target.style.height = `${height + lineHeight}px`
}
}
</script>