美文网首页让前端飞
JS实现无缝滚动

JS实现无缝滚动

作者: 雅玲哑铃 | 来源:发表于2018-12-10 22:53 被阅读13次

    不多说,直接贴代码了

    <!doctype html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title>无缝滚动</title>
            <style type="text/css">
                .wrap{
                    width: 500px;
                    height: 280px;
                    border: 10px red solid;
                    margin: 100px auto;
                    position: relative;
                    overflow: hidden;
                }
                .box{
                    width: 2500px;
                    height: 280px;
                    background-color: gray;
                    position: absolute;
                }
                .item{
                    width: 500px;
                    height: 280px;
                    float: left;
                    line-height: 280px;
                    font-size: 100px;
                    text-align: center;
                    color: white;
                }
                .item1{
                    background-color: pink;
                }
                .item2{
                    background-color: blue;
                }
                .item3{
                    background-color: yellow;
                }
                .item4{
                    background-color: green;
                }
    
            </style>
        </head>
        <body>
            <div class="wrap" >
                <div class="box" style="left:0;">
                    <div class="item item1">1</div>
                    <div class="item item2">2</div>
                    <div class="item item3">3</div>
                    <div class="item item4">4</div>
                    <div class="item item1">1</div>
                </div>
            </div>
        </body>
        <script type="text/javascript">
            var wrap = document.getElementsByClassName('wrap')[0];
            var box = document.getElementsByClassName('box')[0];
            var moveTimer = setInterval(function(){
                var boxLeft = parseInt(box.style.left);
                box.style.left=boxLeft-5+"px";
                if(boxLeft<=-2000){
                    box.style.left="0px";
                }
            },30);
    
            wrap.onmouseover = function(){
                clearInterval(moveTimer);
            }
            wrap.onmouseout = function(){
                moveTimer = setInterval(function(){
                    var boxLeft = parseInt(box.style.left);
                    box.style.left=boxLeft-5+"px";
                    if(boxLeft<=-2000){
                        box.style.left="0px";
                    }
            },30);
            }
        </script>
    </html>
    

    相关文章

      网友评论

        本文标题:JS实现无缝滚动

        本文链接:https://www.haomeiwen.com/subject/ydjjhqtx.html