js实现向左向右无缝轮动

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div1 {
            width: 750px;
            height: 60px;
            margin: 10px auto;
            position: relative;
            background: #cccccc;
            overflow: hidden;
        }

        #div1 ul {
            position: absolute;
            top: 0;
            left: 0;
        }

        #div1 ul li {
            float: left;
            width: 200px;
            height: 50px;
            margin-left: 5px;
            list-style: none;
        }

        #Right {
            width: 50px;
            height: 50px;
            background: blue;
        }

        #Left {
            width: 50px;
            height: 50px;
            background: brown;
        }
    </style>
    <script>
        window.onload = function () {
            var oDiv = document.getElementById('div1');//获取div
            var oUl = document.getElementsByTagName('ul')[0];//获取ul
            var aLi = document.getElementsByTagName('li');//获取li
            var speat = 2//设置轮动的变量
            oUl.innerHTML = oUl.innerHTML + oUl.innerHTML;
            oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px'//ul的宽度
            function timer() {
                //向左轮动的判断
                if (oUl.offsetLeft < -oUl.offsetWidth / 2) {
                    oUl.style.left = '0';
                }
                //向右轮动的判断
                if (oUl.offsetLeft > 0) {
                    oUl.style.left = -oUl.offsetWidth / 2 + 'px'
                }
                oUl.style.left = oUl.offsetLeft + speat + 'px'
            };
            var time = setInterval(timer, 30);
            //鼠标移入停止计时器
            oDiv.onmouseover = function () {
                clearInterval(time)
            };
            //鼠标移出开始计时器
            oDiv.onmouseout = function () {
                time = setInterval(timer, 30);
            };
            //点击向左轮动
            document.getElementById('Left').onclick = function () {
                speat = -2
            }
            //点击向右轮动
            document.getElementById('Right').onclick = function () {
                speat = 2
            }
        }
    </script>
</head>

<body>
    <div id="Left"></div>
    <div id="Right"></div>
    <div id="div1">
        <ul>
            <li style="background: red;"></li>
            <li style="background: rebeccapurple;"></li>
            <li style="background: royalblue;"></li>
            <li style="background: salmon;"></li>
        </ul>
    </div>

</body>

</html>

 

posted @ 2020-05-11 15:25  YH丶浩  阅读(370)  评论(0编辑  收藏  举报