JS图片切换案例

阅读 62

2022-02-15

1、准备工作

(1)照片4张

(2)命名格式统一:p1.png、p2.png、p3.png、p4.png

(3)将4张照片放入image文件里

2、代码如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>图片切换</title>
    <style>
        img {
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <img src="images/image01.jpg" id="flower">
    <br>
    <button id="prev">上一张</button>
    <button id="next">下一张</button>
    <script>
        // 1. 获取元素
        var img = document.querySelector('img')
        var btn1 = document.querySelector('#prev')
        var btn2 = document.querySelector('#next')

        var minIndex = 1,
            maxIndex = 4,
            currentIndex = minIndex;
        // 2. 添加事件
        btn1.onclick = function() {
            //判断编号是否大于4,大于则将最小值赋给当前索引
            if (currentIndex === minIndex) {
                currentIndex = maxIndex;
            } else {
                currentIndex--;
            }
            img.src = 'images/image0' + currentIndex + '.jpg';
            // img.setAttribute('src', `images/image0${currentIndex}.jpg`); //ES6语法
        };
        btn2.onclick = function() {
            //判断编号是否大于4,大于则将最小值赋给当前索引
            if (currentIndex >= maxIndex) {
                currentIndex = minIndex;
            } else {
                currentIndex++;
            }
            img.src = 'images/image0' + currentIndex + '.jpg';
            // img.setAttribute('src', `images/image0${currentIndex}.jpg`); //ES6语法
        };
    </script>
</body>

</html>

精彩评论(0)

0 0 举报