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

打字机动画文本溢出问题求助:文本无法自动换行

解决打字机动画文本溢出不换行问题

问题根源

你代码里的white-space: nowrap是导致文本横向溢出的直接原因——这个属性强制文本始终在一行显示,不会自动换行。同时,基于width变化的打字动画配合固定字符步数(steps(395))的实现逻辑,只适用于单行文本场景,无法适配多行自动换行的需求。

解决方案

方案一:纯CSS逐行打字(快速实现)

调整CSS,移除强制不换行的属性,改用max-height动画实现逐行显示效果:

.aboutMeText{
    font-size: .9rem;
    margin-bottom: 30px;
    border-right: 0.15em solid #18bdec;
    animation: typing 15s steps(10) 1s 1 normal both, blink 1s steps(1) infinite;
    white-space: normal; /* 允许文本自动换行 */
    overflow: hidden;
    width: 100%;
    line-height: 1.5; /* 统一行高,方便计算行数 */
    max-height: 0; /* 初始隐藏所有内容 */
}

@keyframes typing {
    from {
        max-height: 0;
    }
    to {
        max-height: 15rem; /* 根据实际文本行数调整,比如10行×1.5rem行高=15rem */
    }
}

@keyframes blink {
    50% {
        border-color: transparent;
    }
}
  • 注意:需要根据你的实际文本行数,修改steps()的数值和max-height的最终值,确保匹配内容高度。

方案二:JavaScript辅助逐字打字(效果更真实)

如果需要精确的逐字显示+自动换行效果,用JS控制文本逐字符输出是更可靠的方式:

HTML

<p class="aboutMeText" id="typewriter"></p>

JavaScript

// 替换成你的实际文本内容
const typingText = "这里是需要打字显示的多行文本内容,当内容到达容器边缘时会自动换行,完全符合预期效果。";
const typewriterEl = document.getElementById('typewriter');
let charPos = 0;

function typeChar() {
    if (charPos < typingText.length) {
        typewriterEl.textContent += typingText.charAt(charPos);
        charPos++;
        setTimeout(typeChar, 30); // 控制打字速度,数值越小速度越快
    }
}

// 延迟1秒开始打字,对应原动画的1s延迟
setTimeout(typeChar, 1000);

CSS

.aboutMeText{
    font-size: .9rem;
    margin-bottom: 30px;
    border-right: 0.15em solid #18bdec;
    animation: blink 1s steps(1) infinite;
    white-space: normal;
    overflow: hidden;
    width: 100%;
}

@keyframes blink {
    50% {
        border-color: transparent;
    }
}
  • 这个方案完全支持自动换行,打字效果更贴近真实打字机,且无需手动计算行数或字符数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:20:34