效果实现思路:从首位元素滚动到末尾元素,为了让视觉效果看起来数据是闭环的,因此需要将列表数据的首位元素和末尾元素保持一致,保证展示的内容相同。
轮播图名单滚动效果
以下以vue3代码写法给大家做举例,具体细节思路,可留意注释,这里不再重复解释。
<template>
<div>
<div class="banner">
<div :class="runClass" id="run" ref="run">
<div class="flex" v-for="(item,i) in bannerArr" :key="i">{{item.name}}</div>
</div>
</div>
</div>
</template>
<script setup>
import {ref,onMounted} from 'vue'
//轮播列表数据
const bannerArr = ref([{name:'A先生',id:1},{name:'B先生',id:2},{name:'C先生',id:3},{name:'D先生',id:4},{name:'E先生',id:5},{name:'F先生',id:6}])
//给轮播列表尾部追加一条与数组0小标一模一样的数据,形成头尾闭环
bannerArr.value.push(bannerArr.value[0])
//列表长度
const arrLength = bannerArr.value.length
//获取轮播列表dom元素对象 以下简称run对象
// const run = document.getElementById('run')
const run = ref(null)
//动态类名
const runClass = ref('items')
//计时器间隔时间
const intervalTime = 2000
onMounted(()=>{
//获取run对象子集
const runItems = run.value.children
//获取run对象子节点盒子高度
const itemHeight = runItems[0].offsetHeight
//run对象绝对定位top值
let top = 0
setInterval(()=>{
top-=itemHeight //等同于=》 top=top-itemHeight
run.value.style.top=top+'px'
// run.style.top=top+'px'
if(top<=-itemHeight*(arrLength-1)){
setTimeout(()=>{
runClass.value='itemsClose'
top=0
run.value.style.top=top+'px'
// run.style.top=top+'px'
setTimeout(()=>{
runClass.value='items'
},intervalTime/5)//该延迟主要为了解决重置tio为0时过渡效果生效,这样的话会出现列表快速滚动回顶部现象,具体延迟时间可根据实际效果调整
},1000)//原items class带有1秒的过滤时间,因此需要在1秒将过渡效果暂时关闭,然后把run对象top值重置为0,再打开带有过渡效果的class
}
},intervalTime)//每3秒自下而上滚动一次
})
</script>
<style lang="scss" scoped>
.banner{
width: 200px;
height: 80px;
background-color: aqua;
overflow: hidden;
position: relative;
.items{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
transition: all linear 1s;
div{
width: 100%;
height: 100%;
}
}
//用于关闭transition过渡效果
.itemsClose{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
div{
width: 100%;
height: 100%;
}
}
}
</style>
还有什么不明白的可以评论区留言,博主看到后能提供解决思路的会一一回复,觉得文章还不错的点赞收藏关注一波~感谢大家!