我想应用这样的Typewriting效果,我仍然在努力与风格的组件.
我知道我需要定义两个动画,一个用于键入以设置角色动画,另一个用于闪烁以设置插入符号动画.
然后我内联应用:after
伪元素,将插入符号添加到容器元素中.使用Javascript,我可以设置内部元素的文本,并设置包含字符数的--characters变量.此变量用于设置文本的动画.
必要时,需要Wite-space: nowrap
和overflow: hidden
使内容不可见.
App.tsx
import React from 'react';
import { Box } from '@mui/material';
const styles = {
typewriterEffect: {
display: "flex",
justifyContent: "center",
fontFamily: "monospace",
},
"typewriter-effect > text": {
maxWidth: 0,
animation: "typing 3s steps(var(--characters)) infinite",
whiteSpace: "nowrap",
overflow: "hidden",
},
"typewriter-effect:after": {
content: " |",
animation: "blink 1s infinite",
animationTimingFunction: "step-end",
},
"@keyframes typing": {
"75%",
"100%": {
maxWidth: "calc(var(--characters) * 1ch)",
},
},
"@keyframes blink": {
"0%",
"75%",
"100%": {
opacity: 1,
},
"25%": {
opacity: 0,
}
}
};
function Typewriter() {
const typeWriter: HTMLElement | null = document.getElementById('typewriter-text');
const text = 'Lorem ipsum dolor sit amet.';
typeWriter.innerHTML = text;
typeWriter.style.setProperty('--characters', text.length);
return (
<Box style={styles.typewriterEffect}>
<Box class="text" id="typewriter-text"></Box>
</Box>
);
}
export {Typewriter};