淡入淡出按钮单击

时间:2017-07-28 21:47:05

标签: javascript jquery html css

这个淡入淡出动画的CSS样式似乎很好,但它不能用javascript重用。一旦函数执行一次,它就不能再被onClick按钮触发,这是怎么回事?



//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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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);
});
&#13;
.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; } 
}
&#13;
<button class="fadeButton">Button</button>
<div class="fade"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

最好的方法是使用jQuery实现功能 这是切换按钮的淡入和淡出效果的代码。 你可以通过在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>