JavaScript实现简单的图片切换

  <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实现简单的图片切换_第1张图片

你可能感兴趣的:(JavaScript)