天天看點

萬物皆代碼之原生JS實作圖檔無縫輪播

最近項目中有個需求,要求幾張圖不間斷向左滾動,網上一搜一大堆輪播代碼,但是總是與奇葩的客戶需求差那麼一點點,于是隻能自己動手寫了。上代碼

<!DOCTYPE html>
<html>
<head >
    <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>
           

繼續閱讀