这是我的代码:
$("#topbar").click(function () {
$(this).animate({
height: ($(this).height() == 45) ? 20 : 45
}, 200);
});
#topbar {
background: orange;
color: white;
display:block;
width:100%;
text-align:center;
height:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='topbar'>
toggle me
<br>
some explanations
<br>
some more explanation
</div>
如您所见,当您单击橙色框时,它的高度将增加(反之亦然)。但是 45
的高度不足以容纳当前内容。实际上那个盒子的内容是动态的。所以我想设置一个与其内容的高度相同的高度。
我该怎么做?
最佳答案
如果高度是否为 45,则使用条件,然后为 true 条件分配 20,为 false 条件分配 45。相反,请遵循以下代码 -
var collapse = false;
$("#topbar").click(function () {
var ht = (collapse? 20 : this.scrollHeight);
collapse=!collapse;
$(this).animate({
height: ht
},200);
});
#topbar {
background: orange;
color: white;
display:block;
width:100%;
text-align:center;
height:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='topbar'>
toggle me
<br>
some explanations
<br>
some more explanation
</div>
关于javascript - 如何设置元素的高度与其内容相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42360630/