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

时间:2017-02-21 06:57:57

标签: 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对于当前内容来说不够高。实际上,该框的内容是动态的。所以我想设置一个与其内容高度相同的高度。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

如果高度为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>

答案 1 :(得分:1)

这是解决方案。归功于Jai。

&#13;
&#13;
$("#topbar").click(function() {
  $(this).animate({
    height: ($(this).height() == 20) ? this.scrollHeight : 20
  }, 200);

});
&#13;
#topbar {
  background: orange;
  color: white;
  display: block;
  width: 100%;
  text-align: center;
  height: 20px;
}
&#13;
<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
  <br> some more explanation
  <br> some more explanation
  <br> some more explanation<br> some more explanation

</div>
&#13;
&#13;
&#13;