我用CSS3制作了一些动画。
来源很简单。只需打印文本并在4s后消失。
const intro1 = document.getElementsByClassName('intro1')[0]; setTimeout(() => { intro1.classList.remove('fade-in'); intro1.classList.add('fade-out'); }, 3500);
body { margin: 30px 0; padding: 0 15px; } section { display: flex; justify-content: center; align-items: center; background-color: aliceblue; width: 100%; height: 100%; font-size: 2rem; font-weight: 100; } span { text-align: center; position: absolute; } /* Intro animation */ .fade-in { display: inline-block; overflow: hidden; white-space: nowrap; animation: fadeIn 4s; } .fade-out { animation: fadeOut 1s; } @keyframes fadeIn { from { width: 0; } to { width: 100%; } } @keyframes fadeOut { to { opacity: 0; } }
<html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <main> <section> <span class="intro1 fade-in">TEST TEST TEST TEST TEST TEST TEST TEST </span> </section> </main> <script src="src.js"></script> </body> </html>
我定义了 fade-in 和 fade-out .intro1 的类名 'fade-in' .
fade-in
fade-out
.intro1
'fade-in'
延迟3.5秒 setTimeout ,删除类 淡入 淡出 让它消失。
setTimeout
淡入
淡出
当我启动它,文本出现和消失是工作正常。
但当文字消失后,它又像这样出现了。
我不想在文本的不透明度变为0后再次显示。
有什么解决办法吗?
谢谢。
.fade-out { animation: fadeOut 1s; animation-fill-mode: forwards; // that's what you need to add }
关于 animation-fill-mode :
animation-fill-mode
这个 动画填充模式 属性指定动画未播放时(开始之前、结束之后或两者兼有)目标元素的样式。
动画填充模式
“动画填充模式”特性可以具有以下值:
none
forwards -元素将保留由最后一个关键帧设置的样式值(取决于动画方向和动画迭代计数)
forwards
backwards -元素将获得由第一个关键帧设置的样式值(取决于动画方向),并在动画延迟期间保留该值
backwards
both -动画将遵循向前和向后的规则,在两个方向上扩展动画属性
both