一、案例效果:
二、功能点:
实现列表“字幕式”滚动效果;
字幕循环滚动,滚完数据之后会继续从头开始滚动
实现鼠标移入,字幕停止滚动;鼠标移出,字幕继续滚动;
实现滚轮在指定区域内滚动,能够控制控制字幕上下滚动
三、代码:
<template>
<div class="subtitle-container"
ref="container"
@mouseenter="stopScrolling"
@mouseleave="startScrollingOnLeave"
@wheel="handleScroll">
<ul class="subtitle-list"
:style="{ transform: `translateY(-${currentScrollTop}px)` }">
<li v-for="(subtitle, index) in subtitles"
:key="index"
class="subtitle">{{ subtitle }}</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
subtitles: ['在岁月的流逝中,花开花落,却留下了永恒的思念。', '晨曦之光,穿透黑夜的深邃,唤醒沉睡的希望。', '微风轻拂,草木低语,岁月静好,心安如初。', '星空如梦,岁月如歌,心中的孤舟在悠远的彼岸徘徊。', '晨曦之光,穿透黑夜的深邃,唤醒沉睡的希望。', '微风轻拂,草木低语,岁月静好,心安如初。', '情深意浓,宛如一汪清泉,润泽心灵的枯渴。', '山水之间,一念之差,心的旅程,或是波澜壮阔,或是静谧悠长。', '浮生若梦,红尘漫漫,唯有心中的那一抹云彩,永不散去。', '星光璀璨,照亮前行的路途,让希望之花绽放在黑暗中。', '海浪拍岸,千年的沧桑,铭刻着岁月的印记,留下无尽的思绪。', '暮色渐浓,烛光摇曳,思念的火焰在心中燃烧,驱散寂寞的阴霾。'], // 假设这里是你的字幕数据
scrollSpeed: 50, // 滚动速度,单位为毫秒
scrollInterval: null, // 滚动间隔的引用
containerHeight: 0, // 容器高度
subtitleHeight: 0, // 单个字幕的高度
currentScrollTop: 0, // 当前滚动的位置
isHovering: false // 标记鼠标是否悬停在容器上
};
},
mounted () {
this.containerHeight = this.$refs.container.offsetHeight;
this.subtitleHeight = this.$refs.container.querySelector('.subtitle').offsetHeight;
this.startScrolling();
},
methods: {
startScrolling () {
if (!this.isHovering) {
this.scrollInterval = setInterval(() => {
this.currentScrollTop += 1;
if (this.currentScrollTop >= this.subtitleHeight) {
this.currentScrollTop = 0;
this.subtitles.push(this.subtitles.shift());
}
}, this.scrollSpeed);
}
},
stopScrolling () {
clearInterval(this.scrollInterval);
this.isHovering = true;
},
startScrollingOnLeave () {
if (this.isHovering) {
this.isHovering = false;
this.startScrolling();
}
},
handleScroll (event) {
this.currentScrollTop += event.deltaY;
if (this.currentScrollTop < 0) {
this.currentScrollTop = 0;
} else if (this.currentScrollTop > (this.subtitles.length * this.subtitleHeight - this.containerHeight)) {
this.currentScrollTop = this.subtitles.length * this.subtitleHeight - this.containerHeight;
}
}
},
beforeDestroy () {
clearInterval(this.scrollInterval); // 在组件销毁前清除滚动间隔
}
};
</script>
<style>
.subtitle-container {
text-align: center;
margin: 0 auto;
margin-top: 30px;
overflow: hidden;
}
.subtitle-list {
padding: 0;
margin: 0;
list-style-type: none;
}
.subtitle {
line-height: 30px; /* 调整为适当的行高 */
}
</style>