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

为分段打字机效果文本添加Caret(光标)的技术问题求助

分段文本打字机效果的问题修复

问题描述

  • CSS添加的光标对齐到行最右侧,而非文本末尾
  • 所有段落均显示光标,出现多光标堆叠,仅希望当前正在打字的段落显示光标

解决方案代码

HTML(无需修改)

<div id="str">
  <p>Something Cool</p>
  <p>Shows</p>
  <p>Up In here!</p>
</div>

CSS(修改光标样式控制与段落布局)

#str {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 20px;
  height: auto;
  font-family: sans-serif;
  font-size: 40px;
  margin: 20px auto;
  position: relative;
  color: #fff;
  font-weight: bold;
}

#str p {
  overflow: hidden;
  position: relative;
  /* 让段落宽度自适应文本,同时在flex column布局下独占一行 */
  display: inline-block;
}

/* 仅给正在打字的段落添加光标样式 */
#str p.typing {
  border-right: .15em solid orange;
  animation: blink-caret .5s step-end infinite;
}

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

JavaScript(动态控制光标显示)

const paragraphs = document.querySelectorAll('#str p');
let delay = 0;

paragraphs.forEach(p => {
  const text = p.textContent;
  p.textContent = '';

  let index = 0;

  function typeWriter() {
    if (index < text.length) {
      p.textContent += text.charAt(index);
      index++;
      setTimeout(typeWriter, 90);
    } else {
      // 打字完成后移除光标样式
      p.classList.remove('typing');
    }
  }

  // 开始打字前添加光标样式
  setTimeout(() => {
    p.classList.add('typing');
    typeWriter();
  }, delay);
  
  delay += text.length * 90;
});

修改说明

  1. 光标位置修正:

    • 将p标签的display设为inline-block,使其宽度自适应文本内容,同时父容器的flex-direction: column保证每个段落独占一行,光标自然对齐到文本末尾。
  2. 单光标控制:

    • 新增.typing类,集中管理光标样式与闪烁动画。
    • 在JavaScript中,开始打字时为当前段落添加.typing类,打字完成后移除该类,确保只有正在输入的段落显示光标,避免多光标堆叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:00:16