【问题标题】:Fade In and Out on Button Click按钮单击时淡入淡出
【发布时间】:2017-07-28 21:47:04
【问题描述】:

这个淡入淡出动画的 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>

【问题讨论】:

  • .animate() 函数在哪里?
  • “它不能用 javascript 重用” - 因为你没有写 js 代码。
  • @Kinduser 是 -1 标志,最好用你的声望货币购买更多标志。

标签: javascript jquery html css


【解决方案1】:

你只需要点击按钮添加类成员,等到动画完成再移除类。

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>

【讨论】:

  • 谢谢,我需要有关 javascript 的帮助。我无法解析它。
【解决方案2】:

最好的方法是使用 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>

【讨论】:

  • 一键淡入淡出。
猜你喜欢
  • 2020-04-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多