3

我创建了一个切换菜单,如本演示所示。

我添加了一个 css 过渡效果div.nav-menu,并且我曾经max-height:0;这样做过max-height:480px;

当我单击菜单切换以显示菜单时,过渡效果很好。但是,当我再次单击菜单切换以隐藏菜单时,转换不起作用。

我做错了什么?

4

3 回答 3

5

你对 CSS 过渡是错误的。当您添加或删除类时,它们不会动画,只有在您更改 CSS 属性时才会动画。而且您正在直接添加和删除类。

这是您的解决方案:

$( '.menu-toggle' ).on( 'click', function() {
    if(nav.hasClass('toggled-on')) {
       menu.css('maxHeight', 0);
       //^ Here is changed the 'max-height` first so that the 
       //  Transition animation will trigger first
    }
    else menu.css('maxHeight', '480px'); 
         // ^ If not I changed it back to 480px;
} );

// Next I bind on the transaction end event of the element to toggle class
// After it finishes the transistion

menu.on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function() {
    nav.toggleClass( 'toggled-on' );
});

更新小提琴

于 2013-07-08T02:37:34.587 回答
2

There is a much easier way to get the effect you're after.

Working Example

js

$(function() {
    $('.menu-toggle').click(function(){
        if($('.nav-menu').is(':hidden')){ // check to see if menu is hidden
            $('.nav-menu').slideDown();}  // if so slide down
        else{$('.nav-menu').slideUp();}   // else slide up
    });
});

css

html {
    font-size: 100%;
    overflow-y: scroll;
}
body {
    max-width: 860px;
    margin: 0 auto;
    font-family: Helvetica, sans-serif;
}
.main-navigation {
    clear: both;
    min-height: 45px;
    margin-top: 30px;
    position: relative;
}
.menu-toggle {
    cursor: pointer;
    display: inline-block;
    font: bold 16px/1.3;
    margin: 0;
    padding: 10px;
    color: #fff;
    background-color: #1e1e1e;
}

.nav-menu {

    margin: 0;
    background-color: #1e1e1e;
    display: none;
    overflow: hidden;
}

.nav-menu ul {
    display: block;
    margin: 0;
    padding: 0;
    width: 100%;
}
.nav-menu li {
    display: block;
    padding: 10px;
}
.nav-menu li a {
    display: block;
    padding:10px;color:#fff;line-height:1;
    text-decoration: none;
}
.nav-menu li a:hover,.nav-menu li a:focus{background:#272727;}
.toggled-on li a:active{background:#2A8A15;}

API for .slideUp() and API for .slideDown()

于 2013-07-08T02:49:26.903 回答
0

而不是使用最大高度使用高度

.nav-menu {
    margin: 0;
    background-color: #1e1e1e;
    height:0;
    display: block;
    clear: both;
    overflow: hidden;
    -moz-transition:all 350ms cubic-bezier(.42,0,.58,1);
    -ms-transition:all 350ms cubic-bezier(.42,0,.58,1);
    -o-transition:all 350ms cubic-bezier(.42,0,.58,1);
    -webkit-transition:all 350ms cubic-bezier(.42,0,.58,1);
    transition:all 350ms cubic-bezier(.42,0,.58,1);
}
.toggled-on .nav-menu {
    display: block;
    height:480px;
}
于 2020-07-28T08:23:40.163 回答