jquery - CSS Transitions 在 toggleClass() 之后不工作

标签 jquery css css-transitions

我创建了一个切换菜单,如 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' );
});

Updated Fiddle

关于jquery - CSS Transitions 在 toggleClass() 之后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17518258/

相关文章:

jQuery nestedsortable插件默认添加css

css - 即使有垂直滚动,如何在网站底部保持绝对定位的元素?

PHP/HTML/CSS 表格滚动

css - 在所有元素上设置全局背景 CSS3 转换有什么缺点吗?

jquery - 当鼠标离开触发器并向下滑动内容时,如何对向下滑动的内容进行编码以向上滑动?

jquery - CSS 使两个元素具有相同的高度,而不管屏幕大小

javascript - 识别 JavaScript 中的恶意文件上传

asp.net - 将 CSS 标题 Logo 移近布局边缘

html - 如何否定CSS中的运动

javascript - 有没有办法在测验中为 div 设置简单的标志以隐藏问题?