首页 > 解决方案 > Textarea 的父级调整大小在设置高度后停止工作

问题描述

我有一个父 div,里面有一个 textarea。当您动态抓取 textarea 的角以调整其大小时,父 div 也会调整大小。伟大的!

但是,当我使用 javascript 设置 div 的高度时,textarea 将不再调整父 div。

如何使用 Javascript 设置父 div 的高度,并且仍然可以从浏览器调整高度?

这只是一个例子。我在 div 中有其他东西要调整大小,所以我不能只调整 textarea 的大小并将 div 高度保持为自动。

<style>
.parent{
  background-color: blue;
}

.child {
  background-color: red;
 resize: vertical;
}
</style>

<div class="parent" id="container">
<textarea class="child" id="content">
  Hello World!
</textarea>
</div>
<button id="btn">
  Set Height
</button>

<script>
    document.getElementById("btn").addEventListener("click", function() {
    document.getElementById("container").style.height = "100px";
    document.getElementById("content").style.height = "90px";
  });
</script>

标签: javascripthtmlcss

解决方案


您需要做的就是auto在调整其高度后将父 div 的高度设置回。确保你也调整了孩子的高度,否则它会直接跳回到文本区域的大小。

document.getElementById("container").style.height = "auto";

这是完成的代码:

<style>
.parent{
  background-color: blue;
}

.child {
  background-color: red;
 resize: vertical;
}
</style>

<div class="parent" id="container">
<textarea class="child" id="content">
  Hello World!
</textarea>
</div>
<button id="btn">
  Set Height
</button>

<script>
    document.getElementById("btn").addEventListener("click", function() {
    document.getElementById("container").style.height = "100px";
    document.getElementById("content").style.height = "90px";
    document.getElementById("container").style.height = "auto";
  });
</script>


推荐阅读