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

打字机效果问题:光标位置远超文本末端

解决打字机光标超出文本末端的问题

问题根源有两个:

  1. h1是块级元素,默认占满父容器宽度,动画里width:100%会让光标跑到容器最右侧,而非文本末尾。
  2. 块级元素的宽度特性导致动画结束后,光标无法精准对齐文本末端。

修改后的代码如下:

HTML(无需改动)

<div class="title">
   <h1>Hi, I'm ConnerDE</h1>
</div>

CSS 修改方案

.title h1 {
    color: #fff;
    font-family: monospace;
    overflow: hidden;
    border-right: .15em solid orange;
    white-space: nowrap;
    margin: 0 auto;
    letter-spacing: .15em;
    /* 让元素宽度收缩到文本实际宽度 */
    display: inline-block;
    /* 步数对应文本字符总数(含空格、标点),这里"Hi, I'm ConnerDE"共16个字符 */
    animation: typing 3.5s steps(16, end), blink-caret .5s step-end infinite;
}

@keyframes typing {
    from {
        width: 0
    }
    /* 动画结束时宽度适配文本内容 */
    to {
        width: fit-content;
    }
}

@keyframes blink-caret {
    from,
    to {
        border-color: transparent
    }
    50% {
        border-color: orange
    }
}

核心调整说明

  • display: inline-block:取消h1的块级特性,让它的宽度仅包裹文本内容。
  • width: fit-content:确保动画结束后,元素宽度刚好匹配文本,光标自然停在文本末端。
  • 确认steps()的步数和文本字符数一致:数清文本里的每个字符(包括空格、逗号、单引号),能让打字动画的节奏更贴合字符输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:20