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>

效果简单
JavaScript实现超简单的图片切换效果_第1张图片

你可能感兴趣的:(JavaScript小案例,javascript,html,前端)