使用uni-app实现弹幕功能及滚动效果

<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动画属性实现滚动效果。弹幕元素在屏幕底部滚动到顶部后,会重新回到底部进行循环滚动。

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值