1、图片能够自动轮播,

2、鼠标移入,轮播停止;移出继续轮播;

知识点:1、定时器:setInterval();

2、鼠标移入事件:onmouseenter/onmouseover;

鼠标移出事件:onmouseleave/onmouseout;

难点:点击第一张图片,我们想要的效果是鼠标移出后,图片轮播到第二张图片,到事实是轮播到第三张图片。

HTML代码如下:

<div id="div_0">
        <img src="img/bg1.jpg" alt="">
        <ul>
            <li class="active"></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>

css代码如下:

<style>
        #div_0 {
            width: 500px;
            height: 300px;
            margin: 0 auto;
            text-align: center;
            position: relative;
        }
        
        #div_0 img {
            width: 500px;
            height: 300px;
        }
        
        ul {
            display: flex;
            justify-content: space-between;
            width: 400px;
            height: 30px;
            position: absolute;
            bottom: 0;
            left: 0;
            list-style: none;
        }
        
        ul li {
            width: 20px;
            height: 20px;
            background-color: rgba(225, 225, 225, 0.661);
            border-radius: 50%;
        }
        
        .active {
            background-color: aqua;
        }
    </style>

JS代码如下:

<script>
        var index = 0;
        var list = document.querySelectorAll("ul li")

        function changePic() {
            var arr = ["bg1.jpg", "bg2.jpg", "bg3.jpg", "bg4.jpg", "bg5.jpg", "bg6.jpg"]
                //如何更换图片
                //获取到图片img
            var img = document.querySelector("#div_0 img")
                //更改img的src来实现图片切换
            img.src = "img/" + arr[index]


            //获取所有的li标签
            var list = document.querySelectorAll("ul li")
                //先将所有li上面的active进行清除
            for (var i = 0; i < list.length; i++) {
                list[i].classList.remove("active")
            }

            list[index].classList.add("active")
            list[index].onmouseover = function() {
                clearInterval(time)
                console.log(1);
            }
            list[index].onmouseout = function(event) {
                    time = setInterval(changePic, 1000)
                    event.stopPropagation()
                }
                // console.log(index)
            index++
            if (index > 5) {
                index = 0
            }
        }
        var time = setInterval(changePic, 1000)
    </script>

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐