以下是两种在Web上实现弹幕的方法:
1. 使用Vue.js和CSS实现弹幕:
<template>
<div class="barrage-container">
<div v-for="barrage in barrages" :key="barrage.id" class="barrage-item" :style="{ top: barrage.top + 'px', animationDuration: barrage.duration + 's' }">
{{ barrage.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
barrages: [
{ id: 1, content: '弹幕1', top: 0, duration: 5 },
{ id: 2, content: '弹幕2', top: 30, duration: 8 },
{ id: 3, content: '弹幕3', top: 60, duration: 6 },
// 更多弹幕...
]
};
}
};
</script>
<style>
.barrage-container {
position: relative;
height: 200px; /* 弹幕容器高度 */
overflow: hidden;
}
.barrage-item {
position: absolute;
white-space: nowrap;
font-size: 16px;
color: white;
animation: moveBarrage linear infinite;
}
@keyframes moveBarrage {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(-100%);
}
}
</style>
2. 使用Vue 3和CSS实现弹幕:
<template>
<div class="barrage-container">
<div v-for="barrage in barrages" :key="barrage.id" class="barrage-item" :style="{ top: barrage.top + 'px', animationDuration: barrage.duration + 's' }">
{{ barrage.content }}
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const barrages = ref([
{ id: 1, content: '弹幕1', top: 0, duration: 5 },
{ id: 2, content: '弹幕2', top: 30, duration: 8 },
{ id: 3, content: '弹幕3', top: 60, duration: 6 },
// 更多弹幕...
]);
return {
barrages
};
}
};
</script>
<style>
.barrage-container {
position: relative;
height: 200px; /* 弹幕容器高度 */
overflow: hidden;
}
.barrage-item {
position: absolute;
white-space: nowrap;
font-size: 16px;
color: white;
animation: moveBarrage linear infinite;
}
@keyframes moveBarrage {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(-100%);
}
}
</style>