根据文本量将div扩展到特定高度



我已经将div的高度设置为特定值I.E 60px。我希望div的高度可以扩展到80px和100px,这取决于div中的文本量。我已经尝试过几种方法,但到目前为止还没有找到解决方案。

这是我的密码。

HTML
<div id="header">
<div class="header-text">
<h3 class="card-title">Text goes here, Text goes here, Text goes here,  </h3>
<h6 id="support-text">supporting text</h6>


</div>

CSS
#header {
height: 60px;
width: 100%;
background-color: #f4f6f8;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0px 20px;

}

Javascript

function increase() {
var text = parseInt(document.getElementById("header").style.height);
if (text < 80) {
document.getElementById("header").style.height = "60px";
} else if (text == 80) {
document.getElementById("header").style.height = "80px";
} else if (text > 80){
document.getElementById("header").style.height = "100px";
}

increase();

<div id="test"></div>
<script>
const div = document.querySelector('#test'),
divHeight = div.offsetHeight;
if (divHeight === 72) {
div.style.height = '100px';
}
</script>

变量和值只是占位符,您可以更改它。

parseInt(document.getElementById("header").style.height)

元素的样式高度将与您设置的高度完全相同。例如"60px"

如果要查找div的实际高度,请使用.clientHeight而不是.style.height

如果文本超出div的高度,则可以使用.scrollHeight来获取内容的全部高度。

最新更新