<template>
<!-- 无缝滚动效果 -->
<div class="marquee-wrap">
<ul
class="marquee-list" :style="{
transition: 'all 0.5s ease-in-out',
transform: `translateY(${initialTranslateNum}px)`
}"
>
<li
v-for="(item, index) in listData" :key="index" :style="{
transition: 'all 0.5s ease-in-out',
color : getFontColorByIndex(index)
}"
>
{{ item }}
</li>
</ul>
</div>
</template>
<script setup>
import { ref, defineExpose } from 'vue'
const listData = ref(['aaaaaaa', 'bbbbbbbb', 'ccccccccc', 'dddddddd'])
const initialTranslateNum = ref(0)
const currentIndex = ref(0)
const rollUp = () => {
// 超出最大值时,回到第一项
if (currentIndex.value + 1 > listData.value.length - 1) {
currentIndex.value = 0
initialTranslateNum.value = 0
} else {
// 上移
currentIndex.value++
initialTranslateNum.value -= 50
}
}
const rollDown = () => {
// 小于0时,定位到最后一个元素
if (currentIndex.value - 1 < 0) {
currentIndex.value = listData.value.length - 1
initialTranslateNum.value = (listData.value.length - 1) * -50
} else {
currentIndex.value--
initialTranslateNum.value += 50
}
}
defineExpose({
rollUp,
rollDown,
})
const getFontColorByIndex = (index) => {
if (index === currentIndex.value) {
return '#ffffff'
}
return '#a3c5f8'
}
</script>
<style lang="scss" scoped>
.marquee-wrap {
width: 70%;
height: 40px;
//border-radius: 20px;
//background: rgba($color: #000000, $alpha: 0.6);
border-top-style: solid;
border-bottom-style: solid;
border-width: 2px;
margin: 0 auto;
//overflow: hidden;
.marquee-list {
li {
width: 100%;
height: 100%;
margin-bottom: 10px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
padding: 0 20px;
list-style: none;
line-height: 40px;
text-align: center;
color: #fff;
font-size: 18px;
font-weight: 400;
}
}
.animate-up {
transition: all 0.5s ease-in-out;
transform: translateY(-40px);
}
.animate-down {
transition: all 0.5s ease-in-out;
transform: translateY(0px);
}
}
</style>
引用该组件时,调用rollUp, rollDown方法即可