<template>
<view class="container">
<view class="bullet-container">
<view v-for="(bullet, index) in bulletList" :key="index" class="bullet-item">
{{ bullet }}
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
bulletList: ["弹幕1", "弹幕2", "弹幕3", "弹幕4", "弹幕5"],
};
},
mounted() {
this.startBulletAnimation();
},
methods: {
startBulletAnimation() {
const bulletContainer = uni.createSelectorQuery().select(".bullet-container");
bulletContainer.boundingClientRect().exec((rect) => {
const containerHeight = rect[0].height;
const bulletItems = uni.createSelectorQuery().selectAll(".bullet-item");
bulletItems.boundingClientRect().exec((rects) => {
const itemHeight = rects[0][0].height;
const animationDuration = 10; // 动画持续时间,单位为秒
const animationDistance = containerHeight + itemHeight; // 动画滚动距离
const animationDelay = 1; // 动画延迟时间,单位为秒
bulletItems.forEach((item, index) => {
const animation = uni.createAnimation({
duration: animationDuration * 1000,
timingFunction: "linear",
delay: (animationDelay * index) / bulletItems.length * 1000,
});
animation.translateY(-animationDistance).step();
this.$set(this.bulletList, index, animation.export());
});
});
});
},
},
};
</script>
<style>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.bullet-container {
width: 100%;
height: 100%;
overflow: hidden;
}
.bullet-item {
font-size: 16px;
line-height: 24px;
white-space: nowrap;
animation: bulletAnimation linear infinite;
}
@keyframes bulletAnimation {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-100%);
}
}
</style>
这段代码实现了一个简单的弹幕功能,弹幕内容存储在bulletList
数组中,通过遍历数组生成弹幕元素,并使用CSS动画属性实现滚动效果。弹幕元素在屏幕底部滚动到顶部后,会重新回到底部进行循环滚动。