欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript实现简单的图片切换

程序员文章站 2022-05-14 21:07:28
...
  <img src="images/image01.jpg" id="fruit" width="200px" height="200px">
  <br>
  <button id="prev">上一张</button>
  <button id="next">下一站</button>

JavaScript

  var minIndex = 1,
      maxIndex = 4;
      currentIndex = minIndex;
      //下一张切换按钮
    document.querySelector('#next').addEventListener('click', function () {
      if (currentIndex == maxIndex) {
        currentIndex = minIndex;
      } else {
        currentIndex++;
      }
      document.querySelector('#fruit').setAttribute('src', `images/image0${currentIndex}.jpg`)
    });
    //上一张切换按钮
    document.querySelector('#prev').addEventListener('click', function () {
      if (currentIndex == minIndex) {
        currentIndex = maxIndex;
      } else {
        currentIndex--;
      }
      document.querySelector('#fruit').setAttribute('src', `images/image0${currentIndex}.jpg`)
    });

效果

JavaScript实现简单的图片切换