我想应用这样的Typewriting效果,我仍然在努力与风格的组件.

我知道我需要定义两个动画,一个用于键入以设置角色动画,另一个用于闪烁以设置插入符号动画.

然后我内联应用:after伪元素,将插入符号添加到容器元素中.使用Javascript,我可以设置内部元素的文本,并设置包含字符数的--characters变量.此变量用于设置文本的动画.

必要时,需要Wite-space: nowrapoverflow: 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};

推荐答案

Forking 到您的codesandbox以重新创建您的问题.

import { styled } from "@mui/material/styles";

MUI开始创建与Codepen示例相同的样式.

Below is my solution -

https://codesandbox.io/s/automatic-typewriter-effect-stackoverflow-y546o7?file=/src/Typewriter.tsx

Css相关问答推荐

如何使用Bootstrap将图像水平对齐,使其顶部和底部位于同一水平线上?

当弯曲方向设置为列时如何制作等高卡片?

如何在一个父类里面 Select 两个不同的类?

是否有一个 CSS 可以根据字符的高度 for each 字符呈现可变高度?

如何更改导航栏标题中链接的文本 colored颜色 和导航丸中的链接(在shiny 的应用程序中)?

Bootstrap 5 - 更改列顺序时出现问题

如果父项的不透明度小于 1,则背景过滤器不适用

如何在特定元素之前 Select 每个元素

在 中制作等宽的列

在 CSS 或 JavaScript 中反转图像的 colored颜色

li 中的第二行在 CSS-reset 后的项目符号下开始

在 Firefox 中删除额外的按钮间距/填充

Highcharts 图表选项 backgroundColor:'transparent' 在 IE 8 上显示黑色

Flexbox 代码适用于除 Safari 之外的所有浏览器.为什么?

如何计算所需的色调旋转以生成特定 colored颜色 ?

CSS 插入边框

如何在 Chrome 的判断器中添加/插入之前或之后的伪元素?

让 div 扩展全高

使用 CSS go 除图像之间的空间

height: 100% 或 min-height: 100% 用于 html 和 body 元素?