gpt4 book ai didi

javascript - textarea 高度以适应任何键入前的内容

转载 作者:行者123 更新时间:2023-11-28 14:10:50 24 4
gpt4 key购买 nike

有很多“解决方案”可以在输入内容时扩展文本区域。

我需要在任何输入之前设置它的高度,这样整个内容应该在加载页面时可见。

为什么这个微不足道的任务如此复杂?

.txb{
display:block;
width:100%;
resize:none;
outline:none;
}
<textarea class='txb'>
lorem ipsum
dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor
incididunt ut labore
et dolore magna aliqua
</textarea>

最佳答案

您的要求不能只用 CSS 来完成,使用 javascript 很简单。只需添加一个事件来监听页面加载完成,根据内容更新文本区域的高度。

希望我在代码片段中的解释足够清楚。

window.addEventListener('load', event => {
// Select all `textarea` elements and loop through every element
document.querySelectorAll('textarea').forEach(textarea => {
// Update current textarea height based on it's content
textarea.style.height = textarea.scrollHeight + 'px';

// Listen to `input` event and update the textarea height
textarea.addEventListener('input', event => {
// First, remove current inline height
event.target.style.removeProperty('height');

// Then, update it with new content
event.target.style.setProperty('height', event.target.scrollHeight + 'px');
});
});
}, {once: true});
.txb {
display: block;
width: 100%;
resize: none;
outline: none;
}
<textarea class="txb">
lorem ipsum
dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor
incididunt ut labore
et dolore magna aliqua
</textarea>

关于javascript - textarea 高度以适应任何键入前的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com