用uniapp 写一个从右向左滚动的有序弹幕组件兼容h5和小程序
以下是一个简单的从右向左滚动的有序弹幕组件,使用uniapp框架编写,兼容H5和小程序平台。
组件代码:
<template>
<view class="scroll-container">
<view class="scroll-wrap" :style="'animation-duration: ' + duration + 's; animation-play-state: ' + playState">
<view v-for="(item, index) in items" :key="index" class="scroll-item" :style="'animation-delay: ' + (index * delay) + 's; animation-duration: ' + duration + 's; animation-play-state: ' + playState">
{{item}}
</view>
</view>
</view>
</template>
<script>
export default {
props: {
items: {
type: Array,
default: () => []
},
duration: {
type: Number,
default: 10
},
delay: {
type: Number,
default: 0.5
}
},
data() {
return {
playState: 'running'
}
},
mounted() {
this.checkOverflow()
},
methods: {
checkOverflow() {
const wrap = this.$refs.wrap
const container = this.$refs.container
if (wrap && container) {
const wrapWidth = wrap.offsetWidth
const containerWidth = container.offsetWidth
if (wrapWidth > containerWidth) {
const distance = wrapWidth + containerWidth
const duration = distance / 50
this.$refs.wrap.style.animationDuration = duration + 's'
} else {
this.$refs.wrap.style.animationPlayState = 'paused'
}
}
}
}
}
</script>
<style scoped>
.scroll-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.scroll-wrap {
display: inline-block;
animation: scroll 10s linear infinite;
}
.scroll-item {
display: inline-block;
padding-right: 1em;
}
@keyframes scroll {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(-100%);
}
}
</style>
使用方法:
在页面中引入组件,并传入items属性,即弹幕内容数组。
<template>
<view>
<scroll-barrage :items="barrage"></scroll-barrage>
</view>
</template>
<script>
import scrollBarrage from '@/components/scroll-barrage'
export default {
components: {
scrollBarrage
},
data() {
return {
barrage: [
'弹幕1',
'弹幕2',
'弹幕3'
]
}
}
}
</script>
注:在组件中使用了动画,需要注意在小程序中使用动画需要额外配置
原文地址: https://www.cveoy.top/t/topic/ffk4 著作权归作者所有。请勿转载和采集!