html纵向的跑马灯效果,单行文字垂直/水平跑马灯效果

需求描述

接到的需求是这样的:跑马灯效果 一次展示一行文字 循环滚动 文字滚动到视野中停留一秒后滚出。

静态效果如下图,文字从下往上或者从右往左滚动,滚动到此位置时停留一秒(不会传动图...

bVbbZ3v?w=700&h=56

网络上有比较多的多行文字循环滚动的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;

}

horn.png

测试1号
测试2号
测试3号
测试4号
测试5号
测试6号

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值