每秒更改一次图像src

时间:2018-11-12 12:42:59

标签: javascript

我有4张图片,我想制作一个具有以下逻辑的滚动条。每个元素必须:

  1. 弹出
  2. 变得更大
  3. 变小(返回以前的状态)
  4. 消失

我决定为此制作4种不同的动画,并将它们分配给4个不同的类。 我需要做的是无尽的,所以我想出了每秒更改一次图像src的想法。我写了代码,但是没有用。什么也没有发生,也没有错误。

document.addEventListener('DOMContentLoaded', function() {
  setInterval(function() {
    for (var n = 1; n <= 4; n++) {
      if (n == 4) {
        document.getElementsByClassName('animation-slide-4')[0].alt = 'im1';
      } else {
        document.getElementsByClassName('animation-slide-' + n.toString())[0].alt = 'im' + (n + 1).toString();
      }
    }
  }, 1000);
}, false);
@keyframes animation-1 {
  from {
    top: 0px;
    opacity: 0;
  }
  to {
    top: 30px;
    opacity: 0.3;
  }
}

@keyframes animation-2 {
  from {
    top: 30px;
  }
  to {
    opacity: 1;
    top: 70px;
    width: 400px;
  }
}

@keyframes animation-3 {
  from {
    opacity: 1;
    top: 70px;
    width: 400px;
  }
  to {
    opacity: 0.3;
    top: 110px;
    width: 300px;
  }
}

@keyframes animation-4 {
  from {
    opacity: 0.3;
    top: 110px;
  }
  to {
    opacity: 0;
    top: 140px;
  }
}
<img class="slide slide-img animation-slide-1" src="img/1.png" alt="im1"><br>
<img class="slide slide-img animation-slide-2" src="img/2.png" alt="im2"><br>
<img class="slide slide-img animation-slide-3" src="img/4.png" alt="im3"><br>
<img class="slide slide-img animation-slide-4" src="img/3.png" alt="im4"><br>

1 个答案:

答案 0 :(得分:0)

document.addEventListener('DOMContentLoaded', function() {
    function myFunc(n) {
      document.getElementsByClassName('animation-slide-' + n.toString())[0].src = 'img/' + (n + 1).toString() + '.png';
}

  function myFunc1() {
             document.getElementsByClassName('animation-slide-4')[0].src = 'img/1.png';
}
setInterval(function() {
    for (var n = 1; n <= 4; n++) {
      if (n == 4) {
      var m =700;
 setInterval(myFunc1(),m);
 m=m+700;
      } else {
    
        
      setInterval(myFunc(n),m);
       m=m+700;
               
      }
    }
  },1000);
}, false);
@keyframes animation-1 {
  from {
    top: 0px;
    opacity: 0;
  }
  to {
    top: 30px;
    opacity: 0.3;
  }
}

@keyframes animation-2 {
  from {
    top: 30px;
  }
  to {
    opacity: 1;
    top: 70px;
    width: 400px;
  }
}

@keyframes animation-3 {
  from {
    opacity: 1;
    top: 70px;
    width: 400px;
  }
  to {
    opacity: 0.3;
    top: 110px;
    width: 300px;
  }
}

@keyframes animation-4 {
  from {
    opacity: 0.3;
    top: 110px;
  }
  to {
    opacity: 0;
    top: 140px;
  }
}
<img class="slide slide-img animation-slide-1" src="img/1.png" alt="im1"><br>
<img class="slide slide-img animation-slide-2" src="img/2.png" alt="im2"><br>
<img class="slide slide-img animation-slide-3" src="img/4.png" alt="im3"><br>
<img class="slide slide-img animation-slide-4" src="img/3.png" alt="im4"><br>