将CSS动画应用于数组的每个元素

时间:2017-01-17 06:20:25

标签: jquery css-animations

我想显示文本转换的div,每4秒更改一次。每隔四秒钟我就会更改文本,但动画未应用。如何解决这个问题?

以下是js与我的代码:https://jsfiddle.net/zm1dxybr/2/

CSS:

.fadeInDownExit{
    -webkit-animation: fadeInDownExit 8s linear alternate;
    -o-animation: fadeInDownExit 8s linear alternate;
    animation: fadeInDownExit 8s linear alternate;
}

@keyframes fadeInDownExit {
    0%, 100% {
        opacity: 0;
        -webkit-transform: translateY(0px);
        -moz-transform: translateY(0px);
        -ms-transform: translateY(0px);
        -o-transform: translateY(0px);
        transform: translateY(0px);
    }

    10%, 90% {
        opacity: 1;
        -webkit-transform: translateY(20px);
        -moz-transform: translateY(20px);
        -ms-transform: translateY(20px);
        -o-transform: translateY(20px);
        transform: translateY(20px);
    }

}

jQuery的:

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
setInterval(change, 4000);
  function change() { 

                        $('#changeText').html(text[counter]).addClass('fadeInDownExit');
   counter++;
   $('#changeText').html(text[counter - 1]).removeClass('fadeInDownExit');
   if(counter >= text.length) { counter = 0; }
  }

4 个答案:

答案 0 :(得分:0)



<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>toggleClass demo</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <style>
  div {
    width: 100px;
    height: 100px;
    background-color: #ccc;
  }
  .big-blue {
    width: 200px;
    height: 200px;
    background-color: #00f;
  }
  </style>
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
 
<div></div>
 
<script>
$( "div" ).click(function() {
  $( this ).toggleClass( "big-blue", 1000, "easeOutSine" );
});
</script>
 
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在您的代码中看起来像是立即删除了类名,请尝试使用以下代码:

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var intervalstop;
setInterval(change, 8000);
function change() { 
  $('#changeText').html(text[counter]).addClass('fadeInDownExit');
  counter++;
  intervalstop = setInterval(removepclass, 4002);
  if(counter >= text.length) { counter = 0; }
   }
   
 function removepclass() {
   clearInterval(intervalstop);
   $('#changeText').removeClass('fadeInDownExit'); 
   }

答案 2 :(得分:0)

试试这个完美的作品

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
setInterval(change, 4000);
function change() {
 $('#changeText').html(text[counter]).toggleClass('fadeInDownExit');
 counter++;
 $('#changeText').html(text[counter - 1]);
 if(counter >= text.length) { counter = 0; }
   }

答案 3 :(得分:0)

我已经更新了js,因为我们不需要每次都为动画添加类:

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
setInterval(change, 4000);
function change() {

    $('#changeText').html(text[counter % text.length]);
  counter++;
}

https://jsfiddle.net/zm1dxybr/5/