将淡入添加到javascript计时器

时间:2016-11-05 12:44:01

标签: javascript html css

在我的html主体中,我使用的是一个javascript,每隔5秒就会在我的div中写入并更改一行ID为“moto”的文本。

    var text = ["TEXT 1","TEXT 2","TEXT 3","TEXT 4"];
    var counter = 0;
    var elem = document.getElementById("moto");
    ChangeFunction();
    setInterval(ChangeFunction, 5000);
    
    function ChangeFunction() {
        elem.innerHTML = text[counter];
        counter++;
        if(counter >= text.length) { counter = 0; }
    }
    #moto{
      -webkit-transition: all 1s ease-in-out;
      -moz-transition: all 1s ease-in-out;
      -o-transition: all 1s ease-in-out;
      transition: all 1s ease-in-out;
    } 
<div id="moto"></div>
   

我是否需要应用一些java淡入淡出?我宁愿使用CSS ...

2 个答案:

答案 0 :(得分:1)

您可以使用jquery轻松完成此操作,如下所示

var text = ["TEXT 1","TEXT 2","TEXT 3","TEXT 4"];
var counter = 0;
var elem = document.getElementById("moto");
ChangeFunction();
setInterval(ChangeFunction, 5000);

function ChangeFunction() {
    var moto = text[counter++];
    $(elem).fadeOut('slow', function() {
      $(elem).html(moto);
      $(elem).fadeIn('slow');
    });

    if(counter >= text.length) { counter = 0; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moto"></div>

答案 1 :(得分:1)

您根本不需要JavaScript。这是一个纯CSS实现:

@keyframes fade {
  0% {
    opacity: 1;
  }
  50%, 100% {
    opacity: 0;
  }
}
#moto {
  position: relative;
}
#moto div {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  animation: fade 4s 0s infinite alternate-reverse;
}
#moto :nth-child(1) {
  animation-delay: -2s;
}
#moto :nth-child(2) {
  animation-delay: 0s;
}
#moto :nth-child(3) {
  animation-delay: 2s;
}
#moto :nth-child(4) {
  animation-delay: 4s;
}
<div id="moto">
  <div>TEXT 1</div>
  <div>TEXT 2</div>
  <div>TEXT 3</div>
  <div>TEXT 4</div>
</div>