vue实现文字上下滚动效果
需求描述
一个提示功能,可能有多条数据需要显示,但是展示的地方最多显示3条,要求当返回的数据超过3条,就通过上下滚动显示。鼠标移入停止滚动,鼠标移出继续滚动。
问题分析
展示区高度固定,信息列表高度是根据数据条数计算的,可以通过定位,然后修改信息列表的 top 值来实现滚动效果,滚动的最大高度 pos
就是 信息列表的高度 - 展示区高度。
设置一个定时器,每一步step
叠加移动1px
,当移动的距离等于pos
的时候,step
设置为0,从新开始滚动。
但是有个问题:每次step设置为0,定位就跳到第一条,会出现跳跃感,解决方法就是,将数据前三条push到list中,增加三条冗余数据,这样每次滚动到最大高度在跳转后页面跳跃感就消失了。
问题解决
<div class="container" @mouseenter="clearTimer" @mouseleave="scroll">
<div class="box">
<p v-for="(tip, index) in tips" :key="index">{{ tip.desc }}</p>
</div>
</div>
// 获取列表数据
getTips() {
list().then(res => {
let data = res.data
// 超过3条时,增加冗余数据,调用滚动方法
if (data.length > 3) {
let pre3 = chunk(data, 3)[0]
data.push(...pre3)
this.tips = data
this.$nextTick(() => {
this.scroll()
})
} else {
this.tips = data
}
})
},
// 滚动动画
scroll() {
let box = document.querySelector('.box')
let height = box1.clientHeight
let pos = height - 75
this.clearTimer()
this.timer = setInterval(() => {
if (this.step < pos) {
box.style.top = -this.step + 'px'
this.step++
} else if (this.step === pos) {
this.step = 0
}
}, 50)
},
// 清除定时器
clearTimer() {
clearInterval(this.timer)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-05-29 合并两个map数据结构返回一个对象数组