1.通过 transform中的translate 属性进行列表的不断位移。
2.由于列表一直滚动到最后,会出现短暂的区域空白,然后再从头开始滚动。解决这个问题,就是通过在列表后面复制一个相同的列表。
3.以下是通过VUE3实现的一个列表滚动的一个小demo(全部代码)
<template>
<div class="content" @mouseenter="mouseenter" @mouseleave="mouseleave">
<div class="scroll_list" :style="{ transform: `translate(0px,-${scrollTop}px)` }">
<div ref="scrollItemBox">
<div class="scroll_item" v-for="(item, index) in dataList" :key="index">
{{item.name}}
</div>
</div>
<div v-html="copyHtmlData"></div>
</div>
</div>
</template>
<script setup>
import {
ref,
onMounted,
nextTick
} from 'vue';
let timer = ref(null)
const scrollItemBox = ref('')
const scrollBoxHeight = ref(0)
const scrollTop = ref(0)
const speed = ref(15)
const dataList = ref([{
'name': '测试数据第一行',
}, {
'name': '测试数据第二行',
}, {
'name': '测试数据第三行',
}, {
'name': '测试数据第四行',
}, {
'name': '测试数据第五行',
}, {
'name': '测试数据第六行',
}, {
'name': '测试数据第七行',
}, {
'name': '测试数据第八行',
}, {
'name': '测试数据第九行',
}, {
'name': '测试数据第十行',
}, {
'name': '测试数据第十一行',
}])
const copyHtmlData = ref('')
function initScroll() {
nextTick(() => {
copyHtmlData.value = scrollItemBox.value.innerHTML
scrollBoxHeight.value = scrollItemBox.value.offsetHeight
startScroll()
})
}
function mouseenter() {
clearInterval(timer.value);
}
function mouseleave() {
startScroll()
}
function startScroll() {
timer.value = setInterval(scroll, speed.value);
}
function scroll() {
scrollTop.value++
if (scrollTop.value >= scrollBoxHeight.value) {
scrollTop.value = 0
}
}
onMounted(() => {
initScroll()
});
</script>
<style scoped lang="scss">
.content {
height: 400px;
border: 1px solid red;
overflow: hidden;
.scroll_list {
transition: all 0ms ease-in 0s
}
.scroll_item {
height: 50px;
margin-bottom: 10px;
background: pink;
line-height: 40px;
text-align: center;
font-size: 14px;
}
}
</style>