javascript - 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>
解决方案
您需要做的就是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>
推荐阅读
- linux - 使用 systemd-swap 时,swap 使用了大空间,然后使用了 zram
- r - ggplot2中的分组反向条形图
- javascript - 模块中是否有类似“this”的对象?
- javascript - Photoshop 自动化 DoScript 方法
- c# - 在 Linux Ubuntu 上运行 C# 代码 (Visual Studio 2019)
- microsoft-graph-api - Microsoft Graph 中增量链接缓存容量的范围
- javascript - 如何在同一页面中插入多个小部件?
- r - 重组数据框 R - 在一列中收集年份
- java - Swagger UI 无法访问
- powerbi - Power BI 报表生成器、报表生成器、Power BI Desktop、Power BI Desktop (RS) 的用例是什么?