本文将介绍如何使用 uniapp 框架和 vue.js 创建一个从右向左滚动的多行有序弹幕组件,并支持用户发送弹幕功能。该组件兼容 H5 和小程序平台,可用于构建互动性强的应用。

首先,我们需要使用 uniapp 框架和 vue.js 来创建组件。组件需要包含以下功能:

  1. 从右向左滚动的多行有序弹幕
  2. 发送弹幕的功能

以下是组件的代码:

<template>
  <div class='danmu-container'>
    <div
      class='danmu-item'
      v-for='(item, index) in danmuList'
      :key='index'
      :style='{ top: item.top + 'px', right: item.right + 'px' }'
    >
      {{ item.content }}
    </div>
    <div class='danmu-input'>
      <input type='text' v-model='inputValue' @keyup.enter='sendDanmu' />
      <button @click='sendDanmu'>发送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Danmu',
  data() {
    return {
      danmuList: [],
      inputValue: '',
      lineHeight: 20,
      speed: 50,
      maxRows: 5,
      maxLen: 20,
      timer: null
    };
  },
  mounted() {
    this.timer = setInterval(() => {
      this.moveDanmu();
    }, this.speed);
  },
  methods: {
    moveDanmu() {
      this.danmuList.forEach((item) => {
        item.right += 1;
        if (item.right >= this.$el.offsetWidth) {
          this.removeDanmu(item);
        }
      });
    },
    sendDanmu() {
      if (this.inputValue.trim() === '') {
        return;
      }
      const danmu = {
        content: this.inputValue,
        top: this.randomTop(),
        right: 0
      };
      this.danmuList.push(danmu);
      this.inputValue = '';
      if (this.danmuList.length > this.maxRows * this.maxLen) {
        this.danmuList.shift();
      }
    },
    removeDanmu(item) {
      const index = this.danmuList.indexOf(item);
      this.danmuList.splice(index, 1);
    },
    randomTop() {
      return Math.floor(Math.random() * (this.maxRows + 1)) * this.lineHeight;
    }
  }
};
</script>

<style scoped>
.danmu-container {
  position: relative;
  height: 100%;
  overflow: hidden;
}
.danmu-item {
  position: absolute;
  white-space: nowrap;
}
.danmu-input {
  position: absolute;
  bottom: 20px;
  left: 20px;
}
</style>

在这个组件中,我们使用了一个定时器来移动弹幕,每个弹幕都有一个随机的 top 值,表示它出现在哪一行。我们还添加了一个发送弹幕的功能,用户可以在输入框中输入弹幕内容并按下回车或点击发送按钮来发送弹幕。我们还添加了一些配置项,例如弹幕行数,每行最大弹幕数量,弹幕滚动速度等。

在小程序中使用该组件时,需要在小程序的 app.json 文件中声明组件:

"usingComponents": {
  "danmu": "/components/danmu/danmu"
}

在页面中使用组件:

<danmu></danmu>

在 H5 中使用该组件时,需要在 main.js 文件中全局注册组件:

import Danmu from '@/components/danmu/Danmu.vue';
Vue.component('danmu', Danmu);

在页面中使用组件:

<danmu></danmu>

以上便是一个简单的从右向左滚动的多行有序弹幕组件,支持 H5 和小程序。

uniapp 实现多行有序弹幕组件,支持发送弹幕,兼容 H5 和小程序

原文地址: https://www.cveoy.top/t/topic/n7v0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录