CSS Transitions Not working after toggleClass()

泄露秘密 提交于 2019-12-23 20:50:12

问题


I created a toggle-menu, like the DEMO.

I add a css transition effect for div.nav-menu , and i used max-height:0; to max-height:480px; .

When click the menu toggle to show the menu, the transition was working good. But when I click the menu toggle to hide the menu again the transition didn't work now.

What did I did wrong?


回答1:


You are wrong about CSS Transitions. They do not animate when you add or remove class, It will only animate when you change the CSS properties. And You are directly adding and removing classes.

Here is your solution:

$( '.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' );
});

Updated Fiddle




回答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()



来源:https://stackoverflow.com/questions/17518258/css-transitions-not-working-after-toggleclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!