JavaScript实现超简单的图片切换效果

图片名称按数字规律排序的,使用了模板字符串

<img class="image" src="./images/1.jpg" alt="">
    <br>
    <button class="up">上一张</button>
    <button class="down">下一张</button>
    <script>
        var image = document.querySelector('.image')
        var minIndex = 1,
            maxIndex = 4,
            currentIndex = minIndex

        document.querySelector('.down').onclick = function() {
    
    
            if (currentIndex === maxIndex) {
    
    
                currentIndex = minIndex
            } else {
    
    
                currentIndex++
            }
            image.setAttribute('src', `./images/${
      
      currentIndex}.jpg`)
        }
        document.querySelector('.up').onclick = function() {
    
    
            if (currentIndex === minIndex) {
    
    
                currentIndex = maxIndex
            } else {
    
    
                currentIndex--
            }
            image.setAttribute('src', `./images/${
      
      currentIndex}.jpg`)
        }
    </script>

效果简单
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37408390/article/details/124460428