我创建了一个切换菜单,如 this demo 所示.
我为 div.nav-menu
添加了一个 css 过渡效果,我使用了 max-height:0;
到 max-height:480px;
.
当我单击菜单切换按钮以显示菜单时,过渡效果很好。但是,当我再次单击菜单切换按钮以隐藏菜单时,转换不起作用。
我做错了什么?
最佳答案
您对 CSS Transitions 的看法是错误的。它们不会在您添加或删除类时产生动画,它只会在您更改 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' );
});
关于jquery - CSS Transitions 在 toggleClass() 之后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17518258/