JavaScript implements simple picture switching

  <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`)
    });

Effect

insert image description here

Guess you like

Origin blog.csdn.net/m0_37408390/article/details/106309548