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

React中使用typewriter-effect完成动画后无法隐藏光标求助

解决typewriter-effect动画完成后光标无法隐藏的问题

问题原因

你之前通过state修改options.cursor无效,是因为Typewriter组件初始化后不会再响应options里的属性变化,所以即使isAnimationComplete变为true,光标设置也不会更新。

有效解决方案

方案1:使用库内置API直接隐藏光标(推荐)

typewriter-effect的实例提供了hideCursor()方法,直接在动画序列的最后调用即可,无需额外状态管理:

// 修改TestPage中Typewriter的onInit回调
onInit={(typewriter) => {
  typewriter
    .typeString('A simple yet powerful native javascript')
    .pauseFor(300)
    .deleteChars(10)
    .typeString('<strong>JS</strong> plugin for a cool typewriter effect and ')
    .typeString('<strong>only <span style="color: #27ae60;">5kb</span> Gzipped!</strong>')
    .pauseFor(1000)
    .hideCursor() // 动画结束前调用隐藏光标
    .start();
}}

方案2:通过DOM操作强制隐藏光标

如果需要在onComplete事件中处理,直接定位光标元素并修改样式:

const handleAnimationComplete = () => {
  // 光标元素默认类名为Typewriter__cursor
  const cursor = document.querySelector('.Typewriter__cursor');
  if (cursor) {
    cursor.style.display = 'none';
    // 或者用visibility: hidden,保留占位空间
    // cursor.style.visibility = 'hidden';
  }
};

方案3:通过key强制组件重新渲染

如果坚持用state控制,可以给Typewriter组件添加key属性,当状态变化时强制组件重新初始化,应用新的光标设置:

<Typewriter
  key={isAnimationComplete ? 'done' : 'running'} // 状态变化时更新key
  options={{
    delay: 5,
    cursor: isAnimationComplete ? '' : '|',
    onComplete: handleAnimationComplete 
  }}
  onInit={(typewriter) => {
    typewriter
      .typeString('A simple yet powerful native javascript')
      .pauseFor(300)
      .deleteChars(10)
      .typeString('<strong>JS</strong> plugin for a cool typewriter effect and ')
      .typeString('<strong>only <span style="color: #27ae60;">5kb</span> Gzipped!</strong>')
      .pauseFor(1000)
      .start();
  }}
/>

注意:此方案会重新执行整个动画序列,仅适合不需要保留动画状态的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:05:26