<!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>
原生js 跑马灯
最新推荐文章于 2023-02-14 12:01:56 发布