js无缝滚动原理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        ul {
            list-style: none;
        }

        #content {
            width: 400px;
            height: 200px;
            border: 1px solid #000;
            margin: 100px auto;
            overflow: hidden;
            position: relative;
        }

        ul {
            width: 520px;
            overflow: hidden;
            position: absolute;
            left: 0px;
            top: 0px;
        }

        li {
            width: 120px;
            height: 120px;
            background: pink;
            float: left;
            margin-right: 10px;
            text-align: center;
            line-height: 120px;
            font-size: 40px;
            color: #fff;
        }

        #btn {
            /*margin-top:15px;*/
            margin: 135px auto 0;
            width: 210px;
        }

        #btn span {
            display: inline-block;
            width: 100px;
            height: 50px;
            background: palevioletred;
            color: #fff;
            text-align: center;
            line-height: 50px;
        }
    </style>
</head>
<body>
<div id="content">
    <ul id="img-box">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
    <div id="btn">
        <span id="left">向左</span>
        <span id="right">向右</span>
    </div>
</div>
<script>

    var oImgBox = document.getElementById("img-box");
    var oRight = document.getElementById("right");
    var oLeft= document.getElementById("left");
    oImgBox.innerHTML += oImgBox.innerHTML;/*两套li 让显示的时候衔接上*/
    oImgBox.style.width = oImgBox.offsetWidth * 2 + "px"; /*oImgBox宽度*2*/
    var speed = -3;/*初始向左滚动*/

    timer = setInterval(function () {
        if (oImgBox.offsetLeft <= -oImgBox.offsetWidth / 2) {/*offsetWidth获取宽度 offsetLeft获取left*/
            oImgBox.style.left = 0;/*当left<=oImgBox宽度的一半时 让其left值为0*/
        }
        if (oImgBox.offsetLeft > 0) {/*同理*/
            oImgBox.style.left = -oImgBox.offsetWidth / 2 + "px";
        }
        oImgBox.style.left = oImgBox.offsetLeft + speed + "px";
    }, 20);
    oRight.onmouseover = function () {
        speed = 3;  /*正值向右*/
    }
    oLeft.onmouseover = function () {
        speed = -3;
    }
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值