用JS实现 点击并自动切换轮播图

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-26 03:43:40

在这里插入图片描述
不是很难,直接附上代码,有注释
css代码:

* {
            margin: 0;
            padding: 0;

        }

        li {
            list-style: none;
        }

        .wrap {
            width: 1200px;
            margin: 0 auto;
            position: relative;
        }

        .wrap .dbox {
            position: absolute;
            right: 50px;
            bottom: 20px;
            overflow: hidden;
        }

        .dbox li {
            width: 20px;
            height: 20px;
            background: #fff;
            float: left;
            border-radius: 50%;
            margin: 0 10px;
        }

        .dbox .dboxli {
            background: hotpink;
        }

        .dimg img {
            width: 1200px;
            height: 400px;
            display: none;
        }

        .dimg .imgli {
            display: block;
        }

JS代码:

 var wrap = document.getElementsByClassName("wrap")[0];
    var box = document.querySelectorAll(".dbox li");
    var img = document.querySelectorAll(".dimg img");

    for (let i = 0; i < box.length; i++) {
        let li = box[i];
        li.onclick = function () {
            for (var j = 0; j < box.length; j++) {
                box[j].className = "";
                img[j].className = "";
            }
            box[i].className = "dboxli";
            img[i].className = "imgli";
        }
    }

    var index = 0;
    var time = null;
    lunbo();
    function lunbo() {

        time = setInterval(function () {
            index++;
            index = index % 4;
            for (var i = 0; i < box.length; i++) {
                img[i].className = "";
                box[i].className = "";
            }
            img[index].className = "imgli";
            box[index].className = "dboxli";
        }, 1000)
    }
    //鼠标移入
    wrap.onmouseover = function () {
        clearInterval(time)
    }
    //鼠标移出
    wrap.onmouseout = function () {
        lunbo();
    }
    // 解决 当随机点击切换按钮时,图片不会接着往下切换的问题  再for循环一次,把点击的当前下标赋值给上文index
    for (let i = 0; i < box.length; i++) {
        let li = box[i];
        li.onclick = function () {
            index = i;
            for (var j = 0; j < box.length; j++) {
                box[j].className = "";
                img[j].className = "";
            }
            box[i].className = "dboxli";
            img[i].className = "imgli";
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!