You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React文本打字动画:如何处理空格与句号的显示异常?

解决CSS steps()韩文打字动画字符显示异常问题

问题背景

尝试用CSS steps()实现文本打字动画时,遇到如下问题:

  • 文本为“안녕하세요일영일입니다”(无空格、句号,共11个字符),设置steps(11)动画可正常逐个显示字符;
  • 文本改为“안녕하세요 일영일입니다.”(含空格、句号,共13个字符),设置steps(13)却无法精准逐个显示字符。

问题原因

韩文、空格、标点的宽度不一致,而steps(N)是将动画的宽度变化均分为N段,并非按字符数量逐段触发显示。当字符宽度不均时,每一步的宽度增量无法刚好匹配单个字符的宽度,导致动画错位。

解决方案

使用韩文等宽字体,让所有字符(包括空格、标点)的宽度完全一致,这样steps(N)就能精准对应N个字符的显示步骤。

修改后的代码示例

import React from "react";
import styled from "styled-components";

const App = () => {
  return (
    <Wrap>
      <div className="textBx">
        <div className="textWrap">
          <div className="text1">안녕하세요일영일입니다</div>
          <div className="text1">안녕하세요 일영일입니다.</div>
          <div className="btnBx"></div>
        </div>
      </div>
      <div className="imgBx">
        <div className="imgWrap"></div>
      </div>
    </Wrap>
  );
};

export default App;

const Wrap = styled.div`
  margin: 0;
  padding: 0;
  min-height: 100vh;
  display: flex;
  background: linear-gradient(to bottom, #f04a4a, #a326f0);
  /* 替换为韩文等宽字体 */
  font-family: 'Noto Sans Mono KR', monospace;

  .textBx {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .btnBx {
      margin-top: 20px;
      width: 25em;
      height: 4em;
      display: flex;

      .startBtn {
        width: 50%;
        height: 100%;
      }

      .homeBtn {
        width: 30%;
        height: 100%;
        margin-left: 20px;
      }
    }

    .textWrap {
      position: relative;
      left: 40px;
      display: flex;
      flex-direction: column;
      align-items: start;
      justify-content: center;

      .text1 {
        color: white;
        font-size: 4.5em;
        margin-bottom: 20px;
        border-right: 5px solid;
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        /* 对应13个字符的steps参数 */
        animation: typing 2s steps(13), cursor 0.4s step-end infinite alternate;

        @keyframes typing {
          from {
            width: 0;
          }
        }

        @keyframes cursor {
          50% {
            border-color: transparent;
          }
        }
      }

      .text2 {
        color: white;
        font-size: 5.5em;
      }

      .text3 {
        color: white;
        font-size: 5.5em;
      }
    }
  }

  .imgBx {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .imgWrap {
      width: 90%;
      height: 80%;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
`;

补充说明

如果不想更换字体,也可以通过JavaScript动态计算每个字符的累计宽度,生成对应关键帧动画,但等宽字体是最简洁的纯CSS解决方案,兼顾动画精准性和性能。

内容的提问来源于stack exchange,提问作者DgUZH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:24:54