html - css Flex div 随着子文本区域的增长而增长(无jquery)

标签 html css 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>

我希望当文本区域“expand”上的内容创建垂直溢出以扩展父 div,创建垂直滚动。

最佳答案

我认为这不能仅用 CSS 来完成,并且由于您不需要 jQuery,所以这里是一个纯 JS 解决方案。这个想法是在每次更新内容时计算文本区域的高度(调整大小)

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>

关于html - css Flex div 随着子文本区域的增长而增长(无jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47971723/

相关文章:

css - 如何设置输入宽度以匹配占位符文本宽度

html - 如何仅使用 flexbox 制作响应式图像网格?

html - 将 flex 元素右对齐

javascript - 使用 Javascript 在 Firefox 中禁用 Shift + 右键单击

html - 垂直进度条中的居中文本(绝对位置)

javascript - 剪切文本和阴影

css - 元素符号列表元素在 IE7 中消失

php - 如何从下拉字段插入表的多列

html - Bootstrap 专栏全部内容背景色

html - 使用 flexbox 将特定元素居中