JS realizes picture switching

Picture switch

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片切换</title>
    <style>
        * {
     
     
            margin: 0;
            p(index+1)ing: 0;
        }

        #outer {
     
     
            width: 500px;
            /**
            * margin设置元素外边距
            */
            margin: 50px auto;
            p(index+1)ing: 10px;
            background-color: greenyellow;
            text-align: center;
        }
    </style>

    <script type="text/javascript">
        window.onload = function () {
     
     
            /**
             * 点击按钮切换图片
             */
                //获取两按钮
            var prev = document.getElementById("prev");
            var next = document.getElementById("next");
            /**
             * 要切换图片就是修改img标签内的scr属性值
             */
                //获取img标签,getElementsByTagName返回的是类数组,只有一个所以直接取第一个元素
            var img = document.getElementsByTagName("img")[0];
            var info = document.getElementById("info");

            //创建一个数组,用来保存图片路径
            var ingArr = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg"];

            //创建一个变量,来保存正在显示的图片索引
            var index = 0;

            //分别为两按钮绑定单击响应函数
            prev.onclick = function () {
     
     
                //上一张
                index--;
                if (index < 0) {
     
     
                    index = ingArr.length-1;
                }
                info.innerHTML="一共"+ingArr.length+"张图片,这是第"+(index+1)+"张";//使用变量更加灵活不要写死了
                img.src = ingArr[index];
                console.log("上"+index);
            };

            next.onclick = function () {
     
     
                //下一张
                index++;
                if (index >ingArr.length-1){
     
     
                    index = 0;
                }
                info.innerHTML="一共"+ingArr.length+"张图片,这是第"+(index+1)+"张";
                img.src = ingArr[index];
                console.log("下"+index);
            };
        };
    </script>

</head>
<body>
<div id="outer">
    <p id="info">一共五张图片,当前第1张</p>
    <img src="img/1.jpg" alt="冰棍">
    <button id="prev">上一张</button>
    <button id="next">下一张</button>
</div>

</body>
</html>

The renderings are as follows:
Insert picture description here

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-DG1PblyD-1603269036306) (D:%5C%E6%95%99%E5%AD%A6%E8% A7%86%E5%B1%8F%5C%E5%89%8D%E7%AB%AF%5C%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0% 5CJavaScript%E7%AC%94%E8%AE%B0%5Cimage-20201021004556793.png)]

Guess you like

Origin blog.csdn.net/LIUCHUANQI12345/article/details/109204287