问题
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