本文介绍了CSS Flex div随着子textarea的增长而增长(无jquery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下我有以下
div{
padding: 20px;
}
<div style="display:flex; background: gold; flex-direction: column;">
<textarea>Do NOT expand this</textarea>
<textarea class="expand">Expand this baby</textarea>
</div>
我想在textarea上的内容展开"为其扩展父div时产生垂直溢出,而不创建垂直滚动.
I want when content on textarea "expand" creates vertical overflow for it to expand parent div, not to create vertical scroll.
推荐答案
我认为仅靠CSS不能做到这一点,而且由于您不想要jQuery,所以这里是一个纯JS解决方案.这个想法是在每次更新内容时计算文本区域的高度(调整大小)
I think this cannot be done with only CSS, and since you don't want a jQuery one, so here is a pure JS solution. The idea is to calculate the height (resize) the textarea each time you update the content
var tex = document.querySelector('textarea.expand');
tex.addEventListener('keydown', resize);
function resize() {
setTimeout(function() {
tex.style.height = 'auto'; //needed when you remove content so we reduce the height
tex.style.height = tex.scrollHeight + 'px';
}, 0);
}
div {
padding: 20px;
}
<div style="display:flex; background: gold; flex-direction: column;">
<textarea>Do NOT expand this</textarea>
<textarea class="expand">Expand this baby</textarea>
</div>
这篇关于CSS Flex div随着子textarea的增长而增长(无jquery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!