vue弹幕实现暂停
实现Vue弹幕暂停功能的方法
使用CSS动画控制
通过动态切换CSS的animation-play-state属性实现暂停效果。弹幕元素默认设置为animation-play-state: running,暂停时改为paused。

<template>
<div class="danmu-container">
<div
v-for="(item, index) in danmus"
:key="index"
class="danmu-item"
:style="{
'animation-play-state': isPaused ? 'paused' : 'running',
'animation-duration': `${item.speed}s`
}"
>
{{ item.text }}
</div>
<button @click="togglePause">{{ isPaused ? '播放' : '暂停' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
isPaused: false,
danmus: [
{ text: '弹幕1', speed: 5 },
{ text: '弹幕2', speed: 8 }
]
}
},
methods: {
togglePause() {
this.isPaused = !this.isPaused
}
}
}
</script>
<style>
.danmu-item {
position: absolute;
white-space: nowrap;
animation: move linear;
animation-fill-mode: forwards;
}
@keyframes move {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
</style>
使用JavaScript定时器控制
对于通过JavaScript定时器实现的弹幕,可以清除定时器实现暂停,重新创建定时器实现继续播放。
<template>
<div class="danmu-container" ref="container">
<div v-for="(item, index) in visibleDanmus" :key="index" class="danmu-item">
{{ item.text }}
</div>
<button @click="togglePause">{{ isPaused ? '播放' : '暂停' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
isPaused: false,
danmus: ['弹幕1', '弹幕2', '弹幕3'],
visibleDanmus: [],
timer: null,
interval: 1000
}
},
mounted() {
this.startDanmu()
},
methods: {
startDanmu() {
this.timer = setInterval(() => {
if (!this.isPaused) {
this.visibleDanmus.push({
text: this.danmus[Math.floor(Math.random() * this.danmus.length)],
top: Math.random() * 80 + '%'
})
}
}, this.interval)
},
togglePause() {
this.isPaused = !this.isPaused
if (!this.isPaused && !this.timer) {
this.startDanmu()
}
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用第三方库实现
对于使用如rc-bullets等第三方弹幕库的情况,通常库会提供暂停API:
import { BulletScreen } from 'rc-bullets'
export default {
data() {
return {
screen: null,
isPaused: false
}
},
mounted() {
this.screen = new BulletScreen('.danmu-container', { duration: 5000 })
this.screen.push('示例弹幕')
},
methods: {
togglePause() {
this.isPaused ? this.screen.resume() : this.screen.pause()
this.isPaused = !this.isPaused
}
}
}
注意事项
- CSS动画方式性能较好但控制粒度较粗
- JavaScript定时器方式控制更灵活但需注意内存管理
- 暂停时应保留弹幕的当前位置状态
- 考虑弹幕重叠时的显示层级问题
- 移动端需额外处理触摸事件暂停逻辑







