解决方案是使用 AnimationEvent 侦听器。这是我的原始实现:
CSS
• 2 个动画(打开、关闭)
• 2 节课(开课、闭课)
• 2 种状态(溢出隐藏/可见)
打开和关闭总是在动画开始时切换,而隐藏/可见状态在动画结束时会有所不同。
注意:您会看到一个#main-menu 元素:它是一个在 y 轴上带有过渡平移的 UL,因为整个东西是一个菜单向下/向上滑动效果。
@include keyframes(open) {
0% {
height:0;
}
100% {
height:$main_menu_height;
}
}
@include keyframes(close) {
0% {
height:$main_menu_height;
}
100% {
height:0;
}
}
#main-menu-box{
overflow-y:hidden;
height:0; // js
&.closed{
@include animation('close 200ms ease-out 0s');
}
&.opened{
@include animation('open 200ms ease-out 0s 1');
//#main-menu{
// @include translate(0, 0);
//}
}
&.overflow-hidden{
overflow-y:hidden;
}
&.overflow-visible{
overflow-y:visible;
}
}
JS
• 汉堡是一个简单的开/关按钮
• 现在我不得不同时使用 jquery 和 vanilla 选择器..
function poly_event_listener(element, type, callback) {
var pfx = ['webkit', 'moz', 'MS', 'o', ''];
for(var i=0; i<pfx.length; i++) {
if (pfx[i] === '') type = type.toLowerCase();
element.addEventListener(pfx[i]+type, callback, false);
}
}
var hamburger = $('header .hamburger');
var main_menu_box = $('#main-menu-box');
var main_menu_box_std = document.querySelector('#main-menu-box');
var init_menu = true;
hamburger.click(function(){
if(init_menu){
main_menu_box.addClass('opened');
init_menu = false;
return;
}
main_menu_box.toggleClass('opened closed');
});
poly_event_listener(main_menu_box_std,'AnimationStart',function(e){
main_menu_box.addClass('overflow-hidden');
main_menu_box.removeClass('overflow-visible');
});
poly_event_listener(main_menu_box_std,'AnimationEnd',function(e){
// in all the other cases I want hidden:true, visible:false
// if class == closed, since animationend comes after animationstart, the state will already be hidden:true, visible:false
// so non need to check for 'closed' here
if(main_menu_box.hasClass('opened')){
main_menu_box.addClass('overflow-visible');
main_menu_box.removeClass('overflow-hidden');
}
});
这对我有用。