JavaScript onclick click event: click to switch pictures and play them automatically

Put pictures on the page and set four buttons, you can switch pictures by clicking the previous one and the next one (turning to the last one to automatically switch to the first one). The user clicks on autoplay, and it will automatically switch every two seconds (similar to Carousel image), click to stop playing, and the playback will be terminated, and the timer will be used. Look at the renderings first.

 The following is the complete code, if you need it, you can get it yourself!

<body>
    <img id="img" src="./img/0.webp" alt=""><br>
    //给四个button加上点击事件
    <button type="button" onclick="changeImg1()">上一张</button>
    <button type="button" onclick="changeImg()">下一张</button>
    <button type="button" onclick="autoplay1()">自动播放</button>
    <button type="button" onclick="stop1()">停止播放</button>
    <script>
        //获取这个img
        var img = document.getElementById("img");
        //设置一个变量,负责切换图片,作为索引值
        var index = 0;
        //设置一个变量来存储定时器的返回值
        var t = null;
        //定义一个数组来存储照片的地址
        var imgPath = ["./img/0.webp", "./img/1.webp", "./img/2.webp", "./img/3.webp", "./img/4.webp", "./img/5.webp", "./img/6.webp", "./img/7.webp", "./img/8.webp"]
        //下一张
        function changeImg() {
            //我们用三目运算符
            index = index>=(imgPath.length-1)?0:++index;
            img.src = imgPath[index];
            // 或者是if判断
            // if (index>=imgPath.length-1){
            //     index=0;
            //     img.src = `${imgPath[index]}`;
            // } else {
            //      index++;
            //     img.src = `${imgPath[index]}`
            // }
        }
        //上一张
        function changeImg1() {
            //同上
            index= index<=0?(imgPath.length-1) : --index;
            img.src =imgPath[index]
            //下面这个if判断也可以
            // if (index > 0 && index <= 8) {
            //     index--;
            //     img.src = `${imgPath[index]}`;
            // } else if (index <= 0) {
            //     index = 8;
            //     img.src = `${imgPath[index]}`

            // }
        }
        //自动播放
       function autoplay1() {
               t= setInterval(() => {
                   //直接将下一张的方法放在里面
                    changeImg()
                }, 2000)}//2秒调用一次
        function stop1(){
            //清除定时器
            clearInterval(t);
        }
    </script>
</body>

 The effect picture is above!

This is recorded for the convenience of future use, and I hope that the big guys can communicate more, leave a lot of messages, and point out my shortcomings!

Friends in need pick it up! !

Guess you like

Origin blog.csdn.net/A20201130/article/details/122118855