CSS转换在toggleClass()之后不起作用 [英] CSS Transitions Not working after toggleClass()

查看:727
本文介绍了CSS转换在toggleClass()之后不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个切换菜单,例如演示.

I created a toggle-menu, like the DEMO.

我为div.nav-menu添加了一个CSS过渡效果,并且我使用了max-height:0;max-height:480px;.

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.

我做错了什么?

推荐答案

关于CSS Transitions,您错了.它们在添加或删除类时不设置动画,仅当您更改CSS属性时才设置动画. 然后您将直接添加和删除类.

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.

这是您的解决方案:

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

更新了小提琴

这篇关于CSS转换在toggleClass()之后不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆