网络日志

js实现图片预览翻页

原文地址

可以直接复制粘贴打开,图片是在线的,原理简单好懂!

效果

源码

<!DOCTYPE html>
<html>
<!--JQuery在线引用-->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css">
        #lv {
            margin: 0 auto;
            width: 1000px;
            height: 800px;
            background: rgb(150, 235, 180);
            text-align: center;
        }

        #img{
            width: 900px;
            height: 600px;
            margin-top: 60px;
        }

        #pre{
            position: absolute;
            right: 51%;
        }

        #next{
            position: absolute;
            right: 44%;
        }

        #info{
            font-size: x-large;
            padding-top: 30px;
        }
    </style>

</head>
<body>
    <div id="lv">
        <p id="info"></p>
        <img  id ='img' src=""  alt="" />
        <button id="pre">上一张</button>
        <button id="next">下一张</button>
    </div>
</body>
<script type="text/javascript">
    $(function(){
        //获取两个按钮
        var pre = document.getElementById("pre");
        var next = document.getElementById("next");
        //要切换图片就是要修改img 标签的src属性
        //获取img 标签,但是返回的是数组,所以你得操作的是数组中的对象
        var img = document.getElementsByTagName("img")[0];
        //创建一个数组用来保存图片的路径
        var imgArr = ["https://picgo-1253652709.cos.ap-guangzhou.myqcloud.com/560-300.jpg", "https://picgo-1253652709.cos.ap-guangzhou.myqcloud.com/0537AFF0-55BA-4826-9192-BAA8813F0CA7_1_105_c.jpeg", "https://picgo-1253652709.cos.ap-guangzhou.myqcloud.com/615A8F91-1822-445F-903E-5A87FA369977.jpeg"];
        var index = 0;
        var info = document.getElementById("info");
        img.src = imgArr[0];
        info.innerHTML = "总共" + imgArr.length + "照片,现在是第" + (index + 1) + "照片";
        pre.onclick = function () {
            if (--index < 0) {
                index = imgArr.length - 1;
            }
            img.src = imgArr[index];
            info.innerHTML = "总共" + imgArr.length + "照片,现在是第" + (index + 1) + "照片";

        };
        next.onclick = function () {
            if (++index > imgArr.length - 1) {
                index = 0;
            }
            img.src = imgArr[index];
            info.innerHTML = "总共" + imgArr.length + "照片,现在是" + (index + 1) + "照片";
        };
    })
</script>
</html>