无缝滚动实现方式二:用父盒子的scrollLeft 实现

基础样式:

/* 用通配符清除默认样式减少代码量,实际项目应对用到的标签清除默认样式*/
*{margin: 0;padding: 0;list-style: none;}
.inner{width: 320px;height: 180px;position: relative;overflow: hidden;}
#box{width: 320px;height: 180px;padding: 5px;border: 1px solid #ddd;margin: 100px auto 0;}
.inner ul{width: 1000%;position: absolute;top: 0;left: 0;}
.inner ul li{float: left;}
span.span{display: block;width: 320px;height:180px;}
span.span1{background-color: pink;}
span.span2{background-color: red;}
span.span3{background-color: green;}
span.span4{background-color: purple;}
span.span5{background-color: blue;}
html 骨架:

<div id="box">
    <div class="inner">
        <ul>
            <li>
                <a href="#none">
                    <span class='span span1'></span>
                </a>
            </li>
            <li>
                <a href="#none">
                    <span class='span span2'></span>
                </a>
            </li>
            <li>
                <a href="#none">
                    <span class='span span3'></span>
                </a>
            </li>
            <li>
                <a href="#none">
                    <span class='span span4'></span>
                </a>
            </li>
            <li>
                <a href="#none">
                    <span class='span span5'></span>
                </a>
            </li>
        </ul>
    </div>
</div>
javascript 结构:

scroll('box');
function scroll(eleId) {
    var con = document.getElementById(eleId);
    var inner = con.children[0];
    var ul = inner.children[0];
    var ulis = ul.children;
    var unit = inner.clientWidth;
    var l = ulis.length;

    // 克隆节点并且添加到ul里面
    for(var i = 0; i < l; i++) {
        ul.appendChild( ulis[i].cloneNode(true) );
    }
    // 运动
    con.timer = setInterval(move,1);
    function move() {
        inner.scrollLeft ++;
        if(inner.scrollLeft >= l * unit) {
            inner.scrollLeft = 0;
        }
    }
    con.onmouseover = function() {
        clearInterval(con.timer);
    }
    con.onmouseout = function() {
        clearInterval(con.timer);
        con.timer = setInterval(move,1);
    }
}

你可能感兴趣的:(无缝滚动实现方式二:用父盒子的scrollLeft 实现)