旧项目用的 vue3-seamless-scroll 怎么写都不生效,一看源码两年没更新了,不想调试,还是自己写吧,再不济问问GPT都会更快一点
效果图
scroll.vue
<template>
<div class="scroll-container" ref="scrollContainerRef">
<div class="scroll-content" ref="scrollContentRef">
<div
v-for="(item, index) in items"
:key="index"
class="scroll-item"
:style="{ color: fontColor }"
>
{{ item.Content }}
</div>
<div
v-for="(item, index) in items"
:key="'clone-' + index"
class="scroll-item"
:style="{ color: fontColor }"
>
{{ item.Content }}
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
const props = defineProps({
items: {
type: Array,
default: [],
},
});
const fontColor = ref("#ffffff");
const colors = ref([
"#00FFD0",
"#FF8A22",
"#FFFC28",
"#FF6B5C",
"#FFA24F",
"#AAFFA8",
]);
const intervalId = ref();
const getRandomColor = () => {
const randomIndex = Math.floor(Math.random() * colors.value.length);
return colors.value[randomIndex];
};
const changeColor = () => {
fontColor.value = getRandomColor();
};
const scrollContainerRef = ref(null);
const scrollContentRef = ref(null);
const updateDimensions = () => {
const scrollContainerWidth = scrollContainerRef.value.offsetWidth;
const scrollContentWidth = scrollContentRef.value.scrollWidth / 2;
const scrollContentElement = scrollContentRef.value;
scrollContentElement.style.setProperty(
"--scroll-content-width",
`${scrollContentWidth}px`
);
scrollContentElement.style.setProperty(
"--scroll-container-width",
`${scrollContainerWidth}px`
);
};
const startAnimation = () => {
const scrollContentElement = scrollContentRef.value;
scrollContentElement.classList.remove('paused');
scrollContentElement.style.animation = 'none';
scrollContentElement.offsetHeight; // Trigger reflow
scrollContentElement.style.animation = '';
scrollContentElement.classList.add('running');
};
onMounted(() => {
updateDimensions();
window.addEventListener("resize", updateDimensions);
changeColor();
intervalId.value = setInterval(changeColor, 1000);
startAnimation()
});
onUnmounted(() => {
window.removeEventListener("resize", updateDimensions);
clearInterval(intervalId.value);
});
</script>
<style lang="scss" scoped>
.scroll-container {
overflow: hidden;
white-space: nowrap;
width: 100%;
}
.scroll-content {
display: flex;
animation: scroll 20s linear infinite;
}
.scroll-item {
display: inline-block;
font-size: 24px;
height: 29px;
line-height: 29px;
padding-right: 20px;
transition: color 1s;
}
@keyframes scroll {
0% {
transform: translateX(0);
}
100% {
transform: translateX(calc(-1 * var(--scroll-content-width)));
}
}
</style>