效果展示

CSS3 animation(动画)属性

语法:

animation: name duration timing-function delay iteration-count direction fill-mode play-state;

详细参考:


【资料图】

CSS3 animation(动画) 属性

打字机效果的实现

实现一个字一个字移动效果的关键知识:

@keyframes typewriter {    to {        left: 100%;    }}animation: typewriter 3s steps(18) forwards;

实现光标闪烁效果的关键知识

@keyframes flashing {    to {        opacity: 0;    }}animation: flashing .3s ease-out forwards infinite; 

代码示例

下列代码,使用了JS来动态获取文字的个数,从而设置相应的steps值。

思路是:

一个before伪元素来遮挡文字。

一个after伪元素来模拟闪烁的光标。

两个伪元素一起做动画向后移动。

                CSS实现打字机动画效果        
welcome to my home
<script> // 选中app元素 const app = document.querySelector("#app"); // 获取文本长度 const wordNum = app.outerText.length; // 创建一个style标签 const styleElement = document.createElement("style"); styleElement.innerHTML = `#app::before {animation: typewriter ${wordNum * 0.2}s steps(${wordNum}) forwards;}`; styleElement.innerHTML += `#app::after {animation: typewriter ${wordNum * 0.2}s steps(${wordNum}) forwards, flashing .3s ease-out forwards infinite;}`; document.head.appendChild(styleElement); </script>

推荐内容