效果如图(列表内容每隔一定时间进行滚动,鼠标移入停止滚动,鼠标离开继续滚动):
核心思路:
给div
一个固定高度,设置溢出隐藏属性,然后准备一个空的数组temArr
,将数据源拷贝到该空数组temArr
中(为了不影响数据源中的数据),当li
移出自身高度时,将temArr
的第一条数据截取出来,然后追加到temArr
数组的最后,然后再重新给数据源赋值,这样就成了一个死循环,形成了无缝滚动
全部代码如下:
<template>
<div class="box_content">
<header class="header">
<h4>消息通知</h4>
<i class="line"></i>
</header>
<div class="slide-wrapper" @mouseenter="onMouseenter" @mouseleave="onMouseleave">
<ul class="slide-container" ref="uls">
<li class="slide-item" v-for="item in liData" :key="item.id" ref="lis">
<span>{{ item.text }}</span>
<span>{{ item.time }}</span>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
name: 'HelloVue',
data() {
return {
timer: null, // 定时器标识
index: 0,
liData: [ // 数据源
{ id: 1, text: '消息通知11', time: '2023.06.01' },
{ id: 2, text: '消息通知22', time: '2023.06.01' },
{ id: 3, text: '消息通知33', time: '2023.06.02' },
{ id: 4, text: '消息通知44', time: '2023.06.03' },
{ id: 5, text: '消息通知55', time: '2023.06.05' },
{ id: 6, text: '下班了,朋友', time: '2023.06.06' }
]
}
},
mounted() {
this.listRoll()
},
destroyed() {
clearInterval(this.timer)
},
methods: {
listRoll() {
let ulDom = this.$refs.uls
let liDoms = this.$refs.lis
// li移动的最大值, 元素li的高度
let maxL = liDoms[0].offsetHeight
// 列表滚动方法
let move = () => {
this.index++
if (this.index >= maxL) {
this.index = 0
let tempData = [...this.liData] // 拷贝数据源
let tempLiArr = tempData.splice(0, 1) // 当第一个li完全移出列表时截取出第一条数据
tempData.push(...tempLiArr) // 将被截取出的第一条li数据追加到数组最后
this.liData = tempData // 重新给数据源赋值
}
ulDom.style.top = '-' + this.index + 'px' // 每次上移的高度
}
clearInterval(this.timer)
this.timer = setInterval(move, 50)
},
onMouseenter() {
clearInterval(this.timer)
},
onMouseleave() {
this.listRoll()
}
}
}
</script>
样式代码:
<style scoped>
ul {
margin: 0;
padding: 0;
}
ul li {
list-style-type: none;
}
.box_content {
width: 575px;
border: 1px solid #e5e5e5;
border-radius: 6px;
box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.4);
}
.box_content .header {
height: 40px;
line-height: 40px;
}
.box_content h4 {
margin: 0;
margin-left: 10px;
color: #505050;
}
.box_content .line {
display: block;
background-color: #e5e5e5;
width: 100%;
height: 1px;
}
.slide-wrapper {
margin-top: 2px;
width: 575px;
height: 210px;
overflow: hidden;
}
.slide-wrapper .slide-container {
position: relative;
top: 0;
left: 0;
width: 100%;
}
.slide-container .slide-item {
display: flex;
justify-content: space-between;
width: 100%;
height: 50px;
line-height: 50px;
padding: 0 12px 0 12px;
font-size: 14px;
cursor: pointer;
box-sizing: border-box;
}
</style>