万物皆代码之原生JS实现图片无缝轮播

最近项目中有个需求,要求几张图不间断向左滚动,网上一搜一大堆轮播代码,但是总是与奇葩的客户需求差那么一点点,于是只能自己动手写了。上代码


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>图片无缝轮播</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        #box{
            width: 450px;
            height: 300px;
            margin: 0 auto;
            margin-top: 120px;
            position: relative;
            background: mediumvioletred;
            overflow: hidden;
        }
        #box ul{
            position: absolute;
            left: 0;
            top: 0;
        }
        #box ul li{
            float: left;
            width:450px;
            height: 300px;
            list-style: none;
        }
        #box ul li img{
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div class="box" id="box">
        <ul>
            <li><img src="./images/pic1.jpg"></li>
            <li><img src="./images/pic2.jpg"></li>
            <li><img src="./images/pic3.jpg"></li>
            <li><img src="./images/pic4.jpg"></li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    window.onload = function() {
        let box = document.getElementById("box");
        let ul = box.getElementsByTagName("ul")[0];
        let Li = ul.getElementsByTagName("li");

        ul.innerHTML = ul.innerHTML + ul.innerHTML;
        ul.style.width = Li[0].offsetWidth * Li.length + "px";

        function move() {
            if(ul.offsetLeft < -ul.offsetWidth/2){
                 ul.style.left = "0";
             }
             ul.style.left = ul.offsetLeft - 2 + "px";
        }

        let timer = setInterval(move, 75);
        box.onmouseover = function() { // 光标进入,清除定时器
            clearInterval(timer);
        };
        box.onmouseout = function() { // 光标离开,启动timer
            timer = setInterval(move,75);
        };
    }
</script>
</html>


猜你喜欢

转载自blog.csdn.net/weixin_42230045/article/details/80452679