1

我正在尝试创建一个简单的幻灯片。有些事情不太对,我不确定是什么。由于某种原因,正在调用 startSlideShow 函数,但未实现“位置”变量的更改...

var timer = null;
var position = 0;
var images = document.querySelectorAll('.slide img');
for (let i = 0; i < images.length; i++) {
  images[i].src = 'dog' + i + '.jpg';

  var button = document.getElementById('control');
  button.onclick = run;

  function run() {
    if (timer == null) { //stopped or page has just loaded
      timer = setInterval(startSlideShow, 4000);
    } else {
      clearInterval(timer); //this stops animation
      timer = null;
    }

  };

  function startSlideShow() {
    position++;
    images[i].style.left = position + 'px';

  };
}
<div class="slideshow">
  <div class="slide-container">
    <div class="slide">
      <img>
    </div>
    <div class="slide">
      <img>
    </div>
    <div class="slide">
      <img>
    </div>
    <div class="slide">
      <img>
    </div>
  </div>
</div>
<button id="control">Stop/Start</button>

4

1 回答 1

0

你所遵循的逻辑是相反的。图像循环应从按下需要附加单击事件侦听器的按钮开始。因此,迭代的函数需要包含循环。尝试以下代码,它使用带有箭头函数的 IE6 语法。让我知道您是否需要 IE5,但我想您可能很容易弄清楚如何在需要时对其进行转换。

我刚刚重构了解决方案,以便表现得像幻灯片一样:)

这是工作 JsFiddle:https ://jsfiddle.net/0t00oax8/

请尝试以下代码

    var timer = null; 
    var position = 0;
    var images = document.querySelectorAll('.slide img');

    const showNextPic = () => {
           images[ (position > 0) ? (position-1) : 0 ].style = "display:none";
          if( position >= images.length){
             position = 0;
           }

           let imgName =  'dog' + position + '.jpg'
          images[position].src = imgName;
          images[position].alt = imgName;
          images[position].style = "display:block"
          position++;

    }

       var button = document.getElementById('control');

         button.addEventListener('click', () => {
         if (timer == null) { //stopped or page has just loaded
              timer = setInterval(showNextPic, 2000);
         }else {
             clearInterval(timer); //this stops animation
             timer = null;
          }    
       }) ;

希望这可以帮助!

于 2018-05-18T23:31:08.730 回答