需求描述
接到的需求是这样的:跑马灯效果 一次展示一行文字 循环滚动 文字滚动到视野中停留一秒后滚出。
静态效果如下图,文字从下往上或者从右往左滚动,滚动到此位置时停留一秒(不会传动图...
网络上有比较多的多行文字循环滚动的demo,找了一下好像能满足单行并且可停留一秒的比较少(emmm可能我没认真找
下面贴出我的最终解决方案。
解决方案
垂直方向滚动
使用一个定时器 不断改变最外层div的scrollTop,为了能循环滚动,增加一个与con1一样的con2
PS:这里的time选用1000/60是因为想要模拟window.requestAnimationFrame(一般1000ms60帧,当然了,你也可以直接使用requestAnimationFrame代替setInterval,效果更好
单行文字垂直跑马灯效果ul,li{
list-style:none;
display:block;
margin: 0;
padding: 0;
}
#loop-show-box {
width: 300px;
height: 25px;
line-height: 25px;
background: red;
position: absolute;
top: 0;
left: 0;
right: 0;
overflow: hidden;
}
.li-style {
width: 100%;
height: 25px;
text-align: center;
}
- 测试1号
- 测试2号
- 测试3号
- 测试4号
var area = document.getElementById('loop-show-box');
var con1 = document.getElementById('con1');
var con2 = document.getElementById('con2');
var mytimer1 = null;
var mytimer = null;
var time = 1000 / 60;
con2.innerHTML = con1.innerHTML;
function scrollUp () {
if (area.scrollTop >= con1.offsetHeight) {
area.scrollTop = 0;
} else {
if (area.scrollTop % 25 == 0) {
clearInterval(mytimer);
clearInterval(mytimer1);
mytimer1 = setTimeout(function () {
mytimer = setInterval(scrollUp, time);
}, 1000);
}
area.scrollTop++;
}
}
mytimer = setInterval(scrollUp, time);
水平方向滚动
水平方法滚动的具体实现其实跟垂直方向类似的,不同的是要改变的是容器的scrollLeft
单行文字水平跑马灯效果*{
margin: 0;
padding: 0;
}
.container {
width: 400px;
height: 25px;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin: 100px auto;
}
.icon {
width: 15px;
margin-right: 15px;
}
#loop-show-box {
width: 300px;
height: 25px;
line-height: 25px;
background: red;
overflow: auto;
white-space: nowrap;
}
.li-style {
width: 300px;
height: 25px;
text-align: left;
/*使用inline-block的时候两个item之间会存在间距(当然了你可以把它们写在一行以去除这样的间距*/
display: inline-flex;
}
#con1,#con2 {
display: inline-flex;
}
var area = document.getElementById('loop-show-box');
var con1 = document.getElementById('con1');
var con2 = document.getElementById('con2');
var mytimer1 = null;
var mytimer = null;
var time = 1000 / 60;
con2.innerHTML = con1.innerHTML;
function scrollUp () {
if (area.scrollLeft >= con1.offsetWidth) {
area.scrollLeft = 0;
} else {
// 可根据想要的速度调节步长
area.scrollLeft += 2;
if (area.scrollLeft % 300 == 0) {
clearInterval(mytimer);
clearInterval(mytimer1);
mytimer1 = setTimeout(function () {
mytimer = setInterval(scrollUp, time);
}, 1000);
}
}
}
mytimer1 = setTimeout(function () {
mytimer = setInterval(scrollUp, time);
}, 1000)