无缝滚动效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    * { margin:0; padding: 0;}
    .container { position: relative; width: 712px; height: 108px; margin: 50px auto;}
    .box { position: relative; height: 100%; background: red; overflow: hidden;}
    .item { position: absolute; left: 0; top: 0;}
    .item li { float: left; width: 178px; height: 108px; list-style: none; background: #ccc;}
    .item li:nth-child(odd) { background: #f93;}
    .left, .right { position: absolute; width: 108px; height: 108px; font-size: 20px; font-family: 微软雅黑; text-shadow: 1px 1px 0 #fff, 2px 2px 1px rgba(0, 0, 0, 0.2);}
    .left { left: -140px;}
    .right {right: -140px;}
    </style>
</head>
<body>
    <div class="container">
        <button class="left" type="button">往左</button>
        <button class="right" type="button">往右</button>
        <div class="box">    
            <ul class="item">
                <li></li>
                <li></li>
                <li></li>
                <li></li>
            </ul>
        </div>
    </div>
    

<script>
    var box = document.getElementsByClassName('box')[0];
    var item = document.getElementsByClassName('item')[0];
    var li = item.getElementsByTagName('li');
    var toLeft = document.getElementsByTagName('button')[0];
    var toRight = document.getElementsByTagName('button')[1];

    var timer = null;
    //控制滚动速度与滚动方向(整数右、负数为左),默认向左滚动
    var speed = -2;

    //1,复制、拼接
    item.innerHTML = item.innerHTML + item.innerHTML;

    //2,设置ul的宽度使其能容纳所有的li,并在一行显示
    item.style.width = li[0].offsetWidth*li.length+'px';

    //3,设置定时器,移动ul实现无缝滚动
    function move(){
        //当ul滚动至自身宽度的一半时(往右滚动)
        if (item.offsetLeft<-item.offsetWidth/2) {
            item.style.left = '0';
        };
        // 往左滚动
        if (item.offsetLeft>0) {
            item.style.left =-item.offsetWidth/2 + 'px';
        };
        item.style.left = item.offsetLeft+speed+'px';
    }
    //4,触发定时器
    timer = setInterval(move, 30);

    box.onmouseover = function(){
        clearInterval(timer);
    };
    box.onmouseout = function(){
        timer = setInterval(move, 30);
    };

    //控制左右方向
    toLeft.onclick = function(){
        speed = -2;
    };
    toRight.onclick = function(){
        speed = 2;
    };
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/jasontoyell/p/4759088.html