Idiomas compatibles con la página actual:
简体中文用Tailwind做一个文字流动动效组件
CSSTailwind
# Note
Número de palabras 2208
Tiempo aproximado 9 minutes
mar, 9 de junio de 2026, 14:37:00 UTC
效果说明
每个字符从左侧进入、在中段停留、再旋转着从右侧离开,通过给每个字符设置递增的 animation-delay,形成一条文字依次流动的动画。常用于加载页或全屏过渡遮罩。
组件代码
<template>
<!-- 全屏遮罩 -->
<div
:class="['fixed inset-0 z-9999', 'size-full', 'bg-red-500', 'flex justify-center items-center']"
>
<!-- 文字容器 -->
<div
:class="['absolute w-150 h-10', 'left-1/2 top-1/2 -ml-75', 'overflow-visible', 'select-none']"
>
<!-- 单个字符 -->
<div
v-for="(item, index) in animationText"
:key="index"
:style="{ animationDelay: `${index * 0.35}s` }"
:class="[
'animation_text',
'lg:text-4xl text-2xl text-white font-bold text-shadow-xl text-shadow-white',
'absolute w-5 h-10 opacity-0',
]"
>
{{ item }}
</div>
</div>
</div>
</template>
<script setup lang="ts">
const animationText = '...GNIDAOL'
</script>
<style scoped>
.animation_text {
animation: move 4s linear infinite;
}
@keyframes move {
0% {
left: 0;
opacity: 0;
}
35% {
left: 41%;
transform: rotate(0deg);
opacity: 1;
}
65% {
left: 59%;
transform: rotate(0deg);
opacity: 1;
}
100% {
left: 100%;
transform: rotate(-180deg);
opacity: 0;
}
}
</style>
实现要点
- 逐字符渲染:把字符串拆成单个字符,每个字符是独立元素,才能单独控制动画时间。
animation-delay递增:index * 0.35s让后面的字符依次跟上,形成流动感。这个值与总时长4s的比例决定了同时出现的字符数量。- 中段停留:
35%到65%之间left变化很小且opacity保持为 1,让字符在中间有一个可读的停顿。 - 旋转退出:
100%时rotate(-180deg)配合透明度归零,收尾更自然。 overflow-visible:容器宽度固定,字符运动范围超出容器,必须允许溢出,否则会被裁掉。
注意事项
- 字符数影响观感:字符串越长,整体动画周期越难对齐,建议控制在 8~12 个字符。
w-5固定宽度:这个写法假设每个字符等宽。中文或比例字体下字符宽度不同,会显得拥挤或错位,可以改用ch单位或给字符加inline-block后按内容宽度排列。z-9999过高:全屏遮罩层建议使用项目统一的层级变量,避免与其他浮层冲突。- 减少动效偏好:应尊重系统的「减少动态效果」设置,可以通过
@media (prefers-reduced-motion: reduce)关闭动画。 - 性能:动画使用
left而非transform会触发重排,字符较多时建议改为translateX。