单击按钮时淡入和淡出



这个淡入淡出动画的CSS样式看起来很好,但它不能在javascript中重复使用。该功能一旦执行一次,就不能再通过按钮点击触发,有什么办法呢?

//removeClass
//addClass
.elementToFadeInAndOut {
width:200px;
height: 200px;
background: red;
-webkit-animation: fadeinout 4s linear forwards;
animation: fadeinout 4s linear forwards;
opacity: 0;
}
@-webkit-keyframes fadeinout {
50% { opacity: 1; }
}
@keyframes fadeinout {
50% { opacity: 1; }
}
<button onClick="animationfunction()">Button</button>
<div id="icon" class="elementToFadeInAndOut"></div>

您只需要单击按钮添加类成员资格,等待动画完成,然后删除该类。

var div = document.querySelector(".fade");
var btn = document.querySelector(".fadeButton");
btn.addEventListener("click", function(){
div.classList.add("elementToFadeInAndOut");
// Wait until the animation is over and then remove the class, so that
// the next click can re-add it.
setTimeout(function(){div.classList.remove("elementToFadeInAndOut");}, 4000);
});
.fade{
width:200px;
height: 200px;
background: red;
opacity:0;
}
.elementToFadeInAndOut {
animation: fadeInOut 4s linear forwards;
}
@keyframes fadeInOut {
0% { opacity:0; }
50% { opacity:1; } 
100% { opacity:0; } 
}
<button class="fadeButton">Button</button>
<div class="fade"></div>

最好的方法是使用 jQuery for 函数 这是切换按钮的淡入和淡出效果的代码。 您可以通过在jQuery中更改时间(1000(来调整时间谢谢

$(document).ready(function(){
				$('button.btn').click(function(){
					$("div.elementToFadeInAndOut").fadeOut(1000);
$("div.elementToFadeInAndOut").fadeIn(1000);
				});
				});
.elementToFadeInAndOut {
width:200px;
height: 200px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="btn">Button</button>
<div class="elementToFadeInAndOut"></div>

最新更新