2017-02-21 96 views
0

这里是我的代码:如何设置元素的高度与其内容相同?

$("#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对于当前内容来说还不够高。其实这个盒子的内容是动态的。所以我想要设置一个与其内容高度相同的高度。

我该怎么做?

+0

'高度:($(本).height()== 20)? this.scrollHeight:20' – Jai

回答

3

如果height为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

这里是解决方案。信贷给Jai。

$("#topbar").click(function() { 
 
    $(this).animate({ 
 
    height: ($(this).height() == 20) ? this.scrollHeight : 20 
 
    }, 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 
 
    <br> some more explanation 
 
    <br> some more explanation 
 
    <br> some more explanation<br> some more explanation 
 

 
</div>

相关问题