如何在jquery中为height auto设置动画?

时间:2014-06-03 04:45:43

标签: jquery

我制作了垂直下拉菜单。 问题是当我想添加更多子菜单时,我每次都要改变高度。 有没有办法让身高自动?

在这里[http://fiddle.jshell.net/E2EQn/]

这是我的jquery代码

$(document).ready(function(){
    $("#gnb").mouseover(function() {
        $('#header').animate({height: "349px"}, 200 );  // this height need to auto-height   
        $('#subLayer').css({height: "349px"});     // this height need to auto-height
        $('#subLayer ul').css({height: "349px"});  // this height need to auto-height   

    });
    $("#header").mouseleave(function() {
        $(this).animate({height: "96px"}, 200 ); 
    });   
    $("#subLayer").mouseleave(function() {
        $('#header').animate({height: "96px"}, 200 ); 
    }); 

});

1 个答案:

答案 0 :(得分:1)

如果你使用jQuery UI很好,你可以开始使用类而不是显式样式,然后使用改变的addClassremoveClass方法。

例如,如果我们有HTML:

<div id="container">
    <h1>Header</h1>
    <p>Content</p>
</div>

我们可以使用这个CSS:

div, h1, p {
    /* normalize */
    margin: 0;
    font-size: 1em;
    line-height: 1;
}
#container {
    overflow: hidden;
}
#container.collapsed {
    height: 1em;  /* just enough to show the header, but no content */
}

然后,我们可以使用jQuery轻松地将其展开或折叠: JSFiddle

var container = $('#container').addClass('collapsed').hover(function() {
    container.removeClass('collapsed', 200);
}, function() {
    container.addClass('collapsed', 200);
});
相关问题