跑马灯组件 Vue2/Vue3/uni-app/微信小程序
Vue2/Vue3/uni-app/微信小程序源代码资源地址:https://download.csdn.net/download/qiziyiming/92100217
JS动画实现跑马灯组件
css环境:unocss
动画时间更具文本或者插槽跨度自适应
<template><div :class="absolute ? 'absolute w-full h-full top-0 left-0 flex items-center' : ''"><div class="overflow-hidden max-w-full w-full"><a-tooltip class="max-w-full w-full" :placement="placement || 'bottom'"><template #title>{{ value }}</template><div ref="view" class="max-w-full w-full text no-scrollbar"><template v-if="$slots.default"><div ref="text" class="text min-w-full text-center"><slot></slot></div></template><div v-else ref="text" class="text">{{ value }}</div></div></a-tooltip></div></div>
</template><script lang="ts" setup>
import { defineProps, onMounted, ref, watch, onBeforeUnmount, nextTick } from 'vue';
interface Props {value?: string;show?: boolean;absolute?: boolean;duration?: number;placement?: string;
}
const props = defineProps<Props>();
const view = ref<HTMLElement | null>();
const text = ref<HTMLElement | null>();
watch(() => [props.value, props.show],() => {pause();nextTick(() => {initil(view.value as HTMLElement, text.value as HTMLElement);});}
);
onMounted(() => {nextTick(() => {initil(view.value as HTMLElement, text.value as HTMLElement);});
});
const animation = ref<Animation | null>(null);
onBeforeUnmount(() => {pause();
});
function pause() {if (animation.value) {animation.value.pause();animation.value.cancel();}
}
function initil(element: HTMLElement, text: HTMLElement) {pause();const scrollWidth = element.scrollWidth - element.clientWidth;if (scrollWidth > 0) {// node.style.transform = ''const _animation = text.animate([{ transform: 'translateX(0)' }, { transform: `translateX(-${scrollWidth + element.clientWidth + 10}px)` }], {delay: 3000,duration: ((element.scrollWidth / element.clientWidth) * (props.duration || 6) + 2) * 1000,// iterations: Infinity,// direction: 'infinite'});_animation.onfinish = () => {// _animation.pause();setTimeout(() => {_animation.play();}, 2000); // 暂停1秒};animation.value = _animation;// 冒泡型事件element.addEventListener('mouseover', () => {if (animation.value) {animation.value.pause();}});element.addEventListener('mouseout', () => {if (animation.value) {animation.value.play();}});}
}
</script><style lang="less">
.text {word-wrap: normal;text-wrap: normal;white-space: nowrap;
}.no-scrollbar {-ms-overflow-style: none;/* IE和Edge */scrollbar-width: none;/* Firefox */
}.no-scrollbar::-webkit-scrollbar {display: none;/* Chrome, Safari和Opera */
}
</style>
如果跑马灯没效果可以使用相对定位绝对定位设置组件宽度可以解决