简体   繁体   English

JQuery animate()到最大高度

[英]JQuery animate() to maximum height

I have a div with overflow:hidden and a set height. 我有一个overflow:hidden的div overflow:hidden和设定的高度。 When I run animate() , I want the height to animate to the full size. 当我运行animate() ,我想要将高度设置为完整大小的动画。

For example, I have this: 例如,我有这个:

http://jsfiddle.net/aW9k9/ http://jsfiddle.net/aW9k9/

<a href="#" onclick="lol(); return false;">clicky</a>

<div style="height:50px; overflow:hidden;" class="main">
    <div style="height:100px; background:blue;">text</div>
    <div style="height:50px; background:yellow;">text</div>
    <div style="height:50px; background:green;">text</div>
</div>

This example works, but only because I knew the total height of all the elements. 这个例子有效,但只是因为我知道所有元素的总高度。

<script>
    function lol() {
        $("div.main").animate({height:'200px'}, 1000);
    }
</script>

^How can I recreate that without knowing the total animate height? ^如何在不知道总动画高度的情况下重新创建它?

A Fixed version for @MattBall's answer, which use the .outerHeight(true) to include the inner div's margins. @ MattBall答案的固定版本,它使用.outerHeight(true)来包含内部div的边距。

function lol() {
    var $main = $("div.main"),
        totalHeight = 0;

    $main.children().each(function () {
        totalHeight += $(this).outerHeight(true);
    });

    $main.animate({height:totalHeight}, 1000);
}​

If changing html code isn't a problem, you can simply change your html code like this: 如果更改html代码不是问题,您只需更改您的html代码,如下所示:

<a href="#" onclick="lol(); return false;">clicky</a>

<div style="height:50px; overflow:hidden;" class="main">
    <div>
        <div style="height:100px; background:blue;">text</div>
        <div style="height:50px; background:yellow;">text</div>
        <div style="height:50px; background:green;">text</div>
    </div>
</div>

​and you can get height of inner elements like this: 你可以得到这样的内部元素的高度:

$('div.main > div').outerHeight()

and also here is the lol function: 这里也是lol函数:

function lol() { 
    $("div.main").animate({height:$('div.main > div').outerHeight()}, 1000);
}​

You could do programmatically the same thing that you did mentally to come up with the 200px value: sum the height of the div.main > div s. 您可以通过编程方式执行与精神上相同的事情来提出200px值:总和div.main > div的高度。

function lol() {
    var $main = $("div.main"),
        totalHeight = 0;

    $main.children().each(function () {
        totalHeight += $(this).height();
    });

    $main.animate({height: totalHeight}, 1000);
}

http://jsfiddle.net/mattball/CXyKK http://jsfiddle.net/mattball/CXyKK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM