css Flex div随着孩子文本增长而增长(没有jquery)

时间:2017-12-25 20:12:35

标签: html css css3 flexbox

想象一下,我有以下



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>
&#13;
&#13;
&#13;

我想在textarea&#34;扩展&#34;为它创建垂直溢出以扩展父div,以创建垂直滚动。

1 个答案:

答案 0 :(得分:3)

我认为这不能仅用CSS完成,因为你不想要一个jQuery,所以这里是一个纯粹的JS解决方案。我们的想法是每次更新内容时计算textarea的高度(调整大小)

&#13;
&#13;
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);
}
&#13;
div {
  padding: 20px;
}
&#13;
<div style="display:flex; background: gold; flex-direction: column;">
  <textarea>Do NOT expand this</textarea>
  <textarea class="expand">Expand this baby</textarea>
</div>
&#13;
&#13;
&#13;