用uniapp 写一个从右向左滚动的多行有序弹幕组件而且还可以发弹幕兼容h5和小程序
首先,我们需要使用uniapp框架和vue.js来创建组件。组件需要包含以下功能:
- 从右向左滚动的多行有序弹幕
- 发送弹幕的功能
以下是组件的代码:
<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和小程序
原文地址: https://www.cveoy.top/t/topic/fflI 著作权归作者所有。请勿转载和采集!