javascript - 如何设置元素的高度与其内容相同?

标签 javascript jquery html css

这是我的代码:

$("#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/

相关文章:

javascript - backbone.js 中的验证方法不起作用

javascript - 加载这个图片怎么办?

javascript - 如何仅在第 n 次出现时将 TD 字符串拆分为新行

javascript - 如何在带边框的 ext js 中创建 Layout 2X2 布局?

html - 在 div 下有很多空白区域?

javascript - 如何让 ajax 请求的行为类似于标准 HTTP 表单提交

javascript - 根据列选择 d3 数据子集

javascript - 如何检查我的 parentNode 是否是 <a> html 标签 - YUI

javascript - CSS3 关键帧动画在 chrome 中工作,而不是 firefox

jquery - 防止通过更改事件提交表单两次