Vue实现公告循环横向播报组件
<template>
<div class="marquee-container">
<div class="marquee-content" :style="marqueeStyle">
<div class="marquee-text" :style="{ transform: `translateX(${offset}px)` }">
<slot></slot>
</div>
<div class="marquee-text replica" :style="{ transform: `translateX(${replicaOffset}px)` }">
<slot></slot>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
duration: {
type: Number,
default: 20, // 单位秒
},
direction: {
type: String,
default: 'left',
},
},
data() {
return {
offset: 0,
replicaOffset: 0,
interval: null,
};
},
computed: {
marqueeStyle() {
return {
'animation-duration': `${this.duration}s`,
'animation-direction': this.direction,
};
},
},
mounted() {
this.startMarquee();
},
beforeDestroy() {
this.stopMarquee();
},
methods: {
startMarquee() {
if (this.interval) return;
this.interval = setInterval(() => {
if (this.direction === 'left') {
this.offset -= 1;
this.replicaOffset -= 1;
} else {
this.offset += 1;
this.replicaOffset += 1;
}
}, 1000 / 24); // 24 FPS
},
stopMarquee() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
},
},
};
</script>
<style scoped>
.marquee-container {
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
animation-name: marquee;
animation-timing-function: linear;
animation-iteration-count: infinite;
animation-play-state: running;
}
.marquee-text {
display: inline-block;
}
.replica {
position: absolute;
top: 0;
}
@keyframes marquee {
from {
transform: translateX(0);
}
to {
transform: translateX(100%);
}
}
</style>
这个代码实例提供了一个简单的公告文本滚动播报组件,可以通过Vue的slot插槽来提供公告文本。组件使用了CSS动画来实现滚动效果,并且可以通过props来配置滚动的时长和方向。代码中使用了简单的数据绑定和计算属性来动态更新样式,并在组件的生命周期钩子中处理定时器的创建和清理。
评论已关闭