有很多“解决方案”可以在输入内容时扩展文本区域。
我需要在任何输入之前设置它的高度,这样整个内容应该在加载页面时可见。
为什么这个微不足道的任务如此复杂?
.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/