无缝滚动

实现代码:

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
    <div id="btn">
        <a class="left" href="javascript:;" title="往左"></a>
        <a class="right" href="javascript:;" title="往右"></a>
    </div>
    <div id="box">
        <ul>
            <li class="no1">111</li>
            <li class="no2">222</li>
            <li class="no3">333</li>
            <li class="no4">444</li>
        </ul>
    </div>
</body>
</html>

CSS:

<style>
    *{margin: 0px;padding: 0px;}
    body{background: #eee;padding: 100px;}
    li{list-style: none;}
    a{text-decoration: none;}
    #box{width: 600px;height: 150px;border: 1px solid #ccc;box-shadow: 0px 0px 10px #5b5269;border-radius: 5px;position: relative;overflow: hidden;}
    #box ul{width: 600px;height: 130px;position: absolute;top: 0;left: 0;padding: 10px 0;overflow: hidden;}
    #box ul li{float: left;width: 190px;height: 130px;margin:0 5px;}
    #box ul li.no1{background-color: #0281ff;}
    #box ul li.no2{background-color: #27b146;}
    #box ul li.no3{background-color: #7132e4;}
    #box ul li.no4{background-color: #d94013;}
    #btn a{display: block;width: 50px;height: 50px;line-height: 50px;text-align: center;font-size: 30px;background: #6ab5ff;border-radius: 50px;color: #fff;position: absolute;}
    #btn a:hover{background-color: #d94013;}
    #btn a.left{top: 150px;left: 40px;}
    #btn a.right{top: 150px;left: 710px;}
</style>

JS:

<script>
    window.onload=function(){
        var oBox = document.getElementById('btn');
        var aBtn = oBox.getElementsByTagName('a');
        var oUl = document.getElementsByTagName('ul')[0];
        var aLi = oUl.getElementsByTagName('li');
        var iSpeed = -5;

        oUl.innerHTML+=oUl.innerHTML;
        oUl.style.width=(aLi[1].offsetWidth+10) * (aLi.length)+'px';    //offsetWidth不包含margin,所以在这里加上了Li之间的margin值

        function move(){
            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+iSpeed+'px';
        };

        var timer = setInterval(move,30);

        aBtn[0].onclick=function(){
            iSpeed=-5;
        };

        aBtn[1].onclick=function(){
            iSpeed=5;
        }

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

    }
</script>

效果如下图所示:

posted @ 2013-11-20 11:28  白小虫  阅读(161)  评论(0编辑  收藏  举报