原生js 跑马灯

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>跑马灯</title>
    <style>
        .lamp-box {
            width: 500px;
            height: 50px;
            position: relative;
            overflow: hidden;
        }
        .lamp-box ul {
            position: absolute;
            margin: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div class="lamp-box">
        <ul class="lamp">
            <li>第一项</li>
            <li>第二项</li>
            <li>第三项</li>
            <li>第四项</li>
            <li>第五项</li>
        </ul>
    </div>
    <script>
        /* 
            跑马灯构造函数
        */
        function Lamp(el,speed) {
            var _this = this;
            this.dom = document.querySelectorAll(el)[0]; // 获取到滚动盒子
            this.dom.onmouseover = function(){_this.stopCount()}; // 鼠标移动到盒子上停止滚动
            this.dom.onmouseout = function(){_this.count()}; // 鼠标从盒子移开,恢复滚动
            this.box1 = this.dom.getElementsByTagName('*')[0]; // 获取到需要滚动的列表
            this.box2 = this.box1.cloneNode(true); // 克隆列表到新节点
            this.box2.style.top = this.box1.offsetHeight + 'px'; // 设置新节点的位置,为列表的高度
            this.box2.style.position = 'absolute';
            this.dom.appendChild(this.box2)
            this.speed = speed;
            this.count()
        }
        /* 跑马灯定时器方法 */
        Lamp.prototype.count = function() {
            clearTimeout(this.MyMar);
            this.MyMar = setTimeout(() => {
                this.Marquee();
                this.count();
            },this.speed);
        }
        Lamp.prototype.stopCount = function() {
            clearTimeout(this.MyMar);
        }
         /* 
            滚动处理方法
        */
        Lamp.prototype.Marquee = function() {
            if(this.box2.offsetTop - this.dom.scrollTop < 0) {
                this.dom.scrollTop -= this.box2.offsetHeight;
            }else {
                this.dom.scrollTop++;
            }
        }
        /* 初始化跑马灯 */
        var myLamp = new Lamp('.lamp-box',50)
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值