vue实现文字滚动停顿
Vue实现文字滚动停顿效果
在Vue中实现文字滚动并带有停顿效果,可以通过CSS动画或JavaScript定时器实现。以下是两种常用方法:
方法一:使用CSS动画
通过CSS的@keyframes和animation属性实现滚动效果,结合animation-delay实现停顿。
<template>
<div class="scroll-container">
<div class="scroll-text">{{ text }}</div>
</div>
</template>
<script>
export default {
data() {
return {
text: "这是一段需要滚动显示的文字内容..."
}
}
}
</script>
<style>
.scroll-container {
width: 300px;
height: 40px;
overflow: hidden;
position: relative;
}
.scroll-text {
position: absolute;
white-space: nowrap;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0%, 10% {
transform: translateX(100%);
}
90%, 100% {
transform: translateX(-100%);
}
}
</style>
方法二:使用JavaScript定时器
通过Vue的setInterval和clearInterval控制滚动和停顿时间。
<template>
<div class="scroll-container" ref="container">
<div class="scroll-text" :style="{ transform: `translateX(${position}px)` }">
{{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: "这是一段需要滚动显示的文字内容...",
position: 0,
direction: -1,
timer: null,
containerWidth: 0,
textWidth: 0
}
},
mounted() {
this.initScroll();
},
beforeDestroy() {
clearInterval(this.timer);
},
methods: {
initScroll() {
this.containerWidth = this.$refs.container.offsetWidth;
const textElement = this.$refs.container.querySelector('.scroll-text');
this.textWidth = textElement.scrollWidth;
this.timer = setInterval(() => {
if (this.position <= -this.textWidth) {
this.position = this.containerWidth;
setTimeout(() => {
this.startScrolling();
}, 2000); // 停顿2秒
} else {
this.position += this.direction * 2;
}
}, 50);
},
startScrolling() {
// 重新开始滚动
}
}
}
</script>
<style>
.scroll-container {
width: 300px;
height: 40px;
overflow: hidden;
position: relative;
}
.scroll-text {
position: absolute;
white-space: nowrap;
}
</style>
方法三:使用第三方库
可以借助vue-marquee等现成组件快速实现:
-
安装vue-marquee
npm install vue-marquee-text-component -
使用组件
<template> <vue-marquee :duration="10" :repeat="4" :paused="false" > {{ text }} </vue-marquee> </template>
export default { components: { VueMarquee }, data() { return { text: "这是一段需要滚动显示的文字内容..." } } }
```每种方法各有优缺点,CSS动画实现简单但控制不够灵活,JavaScript定时器更可控但代码稍复杂,第三方库最便捷但需要引入额外依赖。根据项目需求选择合适方案。







