css Flex div grow as child textarea grows (no jquery) [duplicate]

前提是你 提交于 2020-01-24 12:28:53

问题


Imagine I have the following

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>

I want when content on textarea "expand" creates vertical overflow for it to expand parent div, not to create vertical scroll.


回答1:


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>


来源:https://stackoverflow.com/questions/47971723/css-flex-div-grow-as-child-textarea-grows-no-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!