YNUtdPlatform/components/MultiColorNoticeBar/index.vue

130 lines
3.0 KiB
Vue
Raw Normal View History

2024-12-10 09:19:55 +08:00
<template>
<view class="notice-bar-container">
<view class="notice-bar-wrapper">
<view class="notice-bar-content" :style="scrollStyle">
<text v-for="(text, index) in textArray" :key="index" :style="textStyle[index]">
{{ text }}
</text>
</view>
</view>
</view>
</template>
<script>
export default {
props: {
textArray: {
type: Array,
default: () => []
},
textStyle: {
type: Array,
default: () => []
},
scrollSpeed: {
type: Number,
default: 1 // 滚动速度,越小越快
}
},
data() {
return {
scrollPosition: 0, // 当前滚动位置
totalWidth: 0, // 内容的总宽度
containerWidth: 0, // 容器的宽度
scrollInterval: null // 滚动定时器
}
},
computed: {
// 滚动样式,动态更新 transform
scrollStyle() {
return {
transform: `translateX(${this.scrollPosition}px)`,
transition: 'transform 0s linear' // 禁用 transition 来避免跳动
}
}
},
mounted() {
this.calculateDimensions() // 计算宽度并启动滚动
},
methods: {
// 获取容器和内容的宽度
calculateDimensions() {
const query = uni.createSelectorQuery().in(this)
// 获取内容的宽度
query
.select('.notice-bar-content')
.boundingClientRect(rect => {
this.totalWidth = rect.width
this.startScroll() // 启动滚动
})
.exec()
// 获取容器的宽度
query
.select('.notice-bar-container')
.boundingClientRect(rect => {
this.containerWidth = rect.width
})
.exec()
},
// 启动滚动效果
startScroll() {
let currentPosition = 0 // 从左侧开始
const speed = this.scrollSpeed
const updateScroll = () => {
// 每次滚动更新位置
currentPosition += speed
// 如果滚动到最右边,重置位置
if (currentPosition >= this.totalWidth) {
currentPosition = 0 // 重置位置到最左边
}
// 更新滚动位置
this.scrollPosition = -currentPosition
}
// 启动定时器进行滚动
if (this.scrollInterval) {
clearInterval(this.scrollInterval) // 清除之前的定时器
}
this.scrollInterval = setInterval(updateScroll, 20) // 每20ms更新一次位置滚动速度由 `scrollSpeed` 控制
}
},
destroyed() {
if (this.scrollInterval) {
clearInterval(this.scrollInterval) // 清理定时器
}
}
}
</script>
<style scoped lang="scss">
.notice-bar-container {
width: 100%;
height: 100%;
overflow: hidden;
white-space: nowrap;
background-color: #fff; /* 可根据需要修改背景颜色 */
}
.notice-bar-wrapper {
display: flex;
align-items: center;
}
.notice-bar-content {
display: flex;
align-items: center;
white-space: nowrap;
height: 56rpx;
line-height: 56rpx;
text {
margin-left: 20rpx;
}
}
</style>