css 如何在KeyUp事件中使文本区域适合文本内容

jaql4c8m  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(113)

所以我有一个textarea

<textarea>
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
</textarea>

我想让textarea适合用户在文本区域中键入的文本,代码如下

const textarea = document.querySelector('textarea')
textarea.addEventListener('keyup', () => {
  textarea.style.height = `${textarea.scrollHeight}px`;
})

当用户向文本区域添加更多文本时,它工作正常。问题是当用户清除内部文本并重新开始键入时,文本区域不会缩小以容纳文本
有办法解决吗?

mzsu5hc0

mzsu5hc01#

试试这个,当值为空时它应该收缩文本区域:

const textarea = document.querySelector('textarea')
textarea.addEventListener('keyup', () => {
  textarea.style.height = textarea.value.length ? `${textarea.scrollHeight}px` : 'auto';
})
iklwldmw

iklwldmw2#

用这种方法,你可以达到你想要的。

function calcHeight(value) {
  let numberOfLineBreaks = (value.match(/\n/g) || []).length;
  // min-height + lines x line-height + padding + border
  let newHeight = 20 + numberOfLineBreaks * 20 + 12 + 2;
  return newHeight;
}

let textarea = document.querySelector("textarea");
textarea.addEventListener("keyup", () => {
  textarea.style.height = calcHeight(textarea.value) + "px";
});

您还可以使用span创建具有所需结果的textarea
超文本:

<span class="textarea"></span>

CSS:

.textarea {
  border: 1px solid #ccc;
  font-family: inherit;
  font-size: inherit;
  padding: 1px 6px;
  display: block;
  width: 100%;
  overflow: hidden;
  resize: both;
  min-height: 40px;
  line-height: 20px;
}

相关问题