当前位置:网站首页>JS picture switching case

JS picture switching case

2022-06-24 18:35:00 Brother Mengfan

JS Picture switching case

One 、 Case needs

Click the previous or next button , The picture will switch

Two 、 case analysis 、

1、 Event source : Button (button)

2、 Event type : Click on (onclick)

3、 Event handler :

(1) First of all, determine the picture number

(2) Picture switching : change img Of src route

3、 ... and 、 preparation

1、 Photo 4 Zhang

2、 The naming format is uniform :p1.png、p2.png、p3.png、p4.png

3、 take 4 Photos in image In the document

Four 、 The code is as follows

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

<head>
    <meta charset="UTF-8">
    <title> Picture switching </title>
    <style>
        img {
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <img src="images/image01.jpg" id="flower">
    <br>
    <button id="prev"> Previous </button>
    <button id="next"> Next </button>
    <script>
        // 1.  Get elements 
        var img = document.querySelector('img')
        var btn1 = document.querySelector('#prev')
        var btn2 = document.querySelector('#next')

        var minIndex = 1,
            maxIndex = 4,
            currentIndex = minIndex;
        // 2.  Add event 
        btn1.onclick = function() {
            // Judge whether the number is greater than 4, Greater than, the minimum value is assigned to the current index 
            if (currentIndex === minIndex) {
                currentIndex = maxIndex;
            } else {
                currentIndex--;
            }
            img.src = 'images/image0' + currentIndex + '.jpg';
            // img.setAttribute('src', `images/image0${currentIndex}.jpg`); //ES6 grammar 
        };
        btn2.onclick = function() {
            // Judge whether the number is greater than 4, Greater than, the minimum value is assigned to the current index 
            if (currentIndex >= maxIndex) {
                currentIndex = minIndex;
            } else {
                currentIndex++;
            }
            img.src = 'images/image0' + currentIndex + '.jpg';
            // img.setAttribute('src', `images/image0${currentIndex}.jpg`); //ES6 grammar 
        };
    </script>
</body>

</html>

原网站

版权声明
本文为[Brother Mengfan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211333166848.html