寻找做这种动画的DRY方法

时间:2018-08-23 21:27:26

标签: javascript jquery css

我正在尝试制作此动画的DRY版本,希望将其循环到无穷大。我应该怎么做才能做到这一点?

<div id="test" contenteditable>testing</div>
<p>Click in the Result window and then press F2.</p>

2 个答案:

答案 0 :(得分:3)

动画定​​时可以通过CSS @keyframes实现。

animationIteration事件中的图像替换可以使用jQuery实现。

那是最多的“干燥”

// An array for the two images to toggle from
images = [
  "https://static.turbosquid.com/Preview/2014/07/03__20_05_28/foot_render_vray_1200x1200_001_main_image.jpg4ff0282c-0d04-4397-a6e0-855b6c0ec9f9Original.jpg",
  "https://content.marketearlybird.com/UploadedContent/Images/Follow%20Button%20Tick.png"
];

//  On animation iteration, change image.
$(".foot").on("webkitAnimationiteration oAnimationiteration msAnimationiteration animationiteration",function(){
  index = ($(this).attr("src") == images[0]) ? 1 : 0;
  $(this).attr("src",images[index]);
});
.foot{
  width:200px;
  animation-name: fadeInOut;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

@keyframes fadeInOut {
  0%{opacity: 0}
  50%{opacity: 1}
  100%{opacity: 0}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img class="foot" src="https://static.turbosquid.com/Preview/2014/07/03__20_05_28/foot_render_vray_1200x1200_001_main_image.jpg4ff0282c-0d04-4397-a6e0-855b6c0ec9f9Original.jpg">

答案 1 :(得分:1)

您始终可以尝试使用setInterval

var interval = setInterval(function(){
  setTimeout(function(){$(".foot").fadeTo(1000, 0);}, 4000);
  setTimeout(function(){$(".foot").attr("src","foot.png")}, 5000);
  setTimeout(function(){$(".foot").fadeTo(1000, 1)},6000)
  setTimeout(function(){$(".foot").fadeTo(1000, 0);}, 10000);
  setTimeout(function(){$(".foot").attr("src","follow.png")}, 11000);
  setTimeout(function(){$(".foot").fadeTo(1000, 1)},12000)
}, 13000);

如果您希望循环停止写入:

clearInterval(interval)