JavaScript在CSS3动画之后不显示 [英] JavaScript display none after CSS3 animation
问题描述
我的id为 mainmenu的div。单击按钮后,我将通过JavaScript向CSS3过渡添加(通过向#mainmenu中添加过渡并创建将添加到div元素的.fadein和.fadeout类)。代码:
I have div with id='mainmenu'. I'm adding CSS3 transition to it by JavaScript after button click (by adding 'transition' to #mainmenu and by creating class .fadein and .fadeout that will be added to the div element). Code:
<div id='mainmenu'></div>
<button id="btn1">Click me1</button>
<button id="btn2">Click me2</button>
#mainmenu {
width:100px;
height:100px;
background:#eee;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
transition: opacity 1s;
}
.fadeout {
opacity:0;
}
.fadein {
opacity:1;
}
var menu = document.getElementById('mainmenu'),
btn1 = document.getElementById('btn1'),
btn2 = document.getElementById('btn2');
btn1.addEventListener('click', function() {
menu.className = 'fadeout';
}
btn2.addEventListener('click', function() {
menu.className = 'fadein';
}
问题在于,现在我要添加无显示并阻止渐变和淡入选项,因此,在淡出动画div之后应无显示,并在淡入显示块之后:
The problem is that now I want to add display none and block to fadeout and fadein option. So after the fadeout animation div should get display none, and after fadein display block:
btn1.addEventListener('click', function() {
menu.className = 'fadeout';
menu.style.display = 'none';
}
btn2.addEventListener('click', function() {
menu.className = 'fadein';
menu.style.display = 'block';
}
不幸的是,该动画没有显示并阻止执行,因此该动画无法正常工作(元素获取不显示任何内容,而没有不透明度动画。)我首先要使动画具有不透明度,然后再显示该元素不显示/不显示任何块。会吗我只能使用纯JavaScript(不能使用jQuery等)。
Unfortunately, the display none and block executes with the animation, so the animation isn't working (element gets display none, without the opacity animation). I want first the animation with opacity, and after that display none/block for the element. Is there any way to do it? I can use only pure JavaScript (no jQuery etc.).
推荐答案
您需要使用 setTimeout( )
和 menu.style.display = none;
,以便让淡入淡出在触发样式之前完成工作.display
。
You need to use setTimeout()
with menu.style.display = "none";
in order to let fade do it's job before you trigger style.display
.
btn1.addEventListener('click', function() {
menu.className = 'fadeout';
setTimeout(function() {
$(menu).css('display', 'none');
}, 1000);
}
btn2.addEventListener('click', function() {
menu.className = 'fadein';
setTimeout(function() {
$(menu).css('display', 'block');
}, 1000);
}
这篇关于JavaScript在CSS3动画之后不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!