当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript实现简单的图片切换功能

JavaScript实现简单的图片切换功能

2020年04月10日  | 移动技术网IT编程  | 我要评论
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>图片切换</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 200px;
            height: 300px;
            margin: 50px auto;
            padding: 20px;
            background-color: skyblue;
            text-align: center;
        }
        img{
            width: 200px;
            height: 200px;
            margin: 20px 0;
        }
    </style>
    <script>
        // 存储照片地址的数组
        let imgarr = ["https://images.cnblogs.com/cnblogs_com/tomhe789/1693260/o_200409051704animal1.png", "https://images.cnblogs.com/cnblogs_com/tomhe789/1693260/o_200409051711animal2.png", "https://images.cnblogs.com/cnblogs_com/tomhe789/1693260/o_200409051717animal3.png", "https://images.cnblogs.com/cnblogs_com/tomhe789/1693260/o_200409051722animal4.png", "https://images.cnblogs.com/cnblogs_com/tomhe789/1693260/o_200409051726animal5.png"];

        // 照片的索引
        let index = 0;
        window.onload = function() {
            let op = document.getelementsbytagname("p")[0];
            op.innerhtml = "一共有" + imgarr.length + "张照片,这是第" + (index+1) +"张";

            let oimg = document.getelementsbytagname("img")[0];
            let oprev = document.getelementsbyclassname("prev")[0];
            let onext = document.getelementsbyclassname("next")[0];

            // 点击上一张响应事件
            oprev.onclick = function () {
                index--;
                //实现照片循环
                if (index < 0) {
                    index = imgarr.length-1;
                }
                op.innerhtml = "一共有" + imgarr.length + "张照片,这是第" + (index+1) +"张";
                oimg.src = imgarr[index];

            };

            // 点击下一张响应事件
            onext.onclick = function () {
                index++;
                //实现照片循环
                if (index >= imgarr.length) {
                    index = 0;
                }
                op.innerhtml = "一共有" + imgarr.length + "张照片,这是第" + (index+1) +"张";
                oimg.src = imgarr[index];
            };
        };
    </script>
</head>
<body>
    <div class="box">
        <p></p>
        <img src="../../images/animal1.png" alt="">
        <button class="prev">上一张</button>
        <button class="next">下一张</button>
    </div>
</body>
</html>

最终的效果
在这里插入图片描述

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网