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

将CSS首页开场打字动画转为JavaScript实现并过渡到首页

用JavaScript实现打字动画并添加首页过渡效果

1. 基础HTML结构

保留原有的打字容器,同时添加首页容器(初始隐藏):

<div class="wrapper">
  <div class="typing-demo"></div>
</div>
<div id="homepage" style="display: none;">
  <!-- 替换成你的首页内容 -->
  <h1>Welcome to My Homepage</h1>
</div>

2. 简化后的CSS

只保留布局和基础样式,动画逻辑交给JavaScript:

.wrapper {
  height: 100vh;
  display: grid;
  place-items: center;
  transition: opacity 0.5s ease-out; /* 用于过渡的动画 */
}

.typing-demo {
  white-space: nowrap;
  overflow: hidden;
  border-right: 3px solid;
  font-family: monospace;
  font-size: 2em;
}

#homepage {
  height: 100vh;
  display: grid;
  place-items: center;
  transition: opacity 0.5s ease-in;
}

3. JavaScript实现打字+光标闪烁+首页过渡

这段代码会复刻原CSS的打字效果,完成后自动过渡到首页:

const typingEl = document.querySelector('.typing-demo');
const homepage = document.getElementById('homepage');
const targetText = "Hello, I'm Typing!"; // 替换为你需要的文本
const typeInterval = 90; // 对应原CSS 2秒打22个字符的速度(2000/22≈90)
let currentChar = 0;

// 打字逻辑
function type() {
  if (currentChar < targetText.length) {
    typingEl.textContent += targetText[currentChar];
    currentChar++;
    setTimeout(type, typeInterval);
  } else {
    // 打字完成后等待1.5秒,再触发首页过渡
    setTimeout(triggerHomepageTransition, 1500);
  }
}

// 光标闪烁逻辑
function blinkCursor() {
  typingEl.style.borderRightColor = typingEl.style.borderRightColor === 'transparent' ? 'currentColor' : 'transparent';
  setTimeout(blinkCursor, 500);
}

// 首页过渡逻辑
function triggerHomepageTransition() {
  // 隐藏打字界面
  document.querySelector('.wrapper').style.opacity = '0';
  setTimeout(() => {
    document.querySelector('.wrapper').style.display = 'none';
    // 显示首页并淡入
    homepage.style.display = 'grid';
    homepage.style.opacity = '0';
    setTimeout(() => homepage.style.opacity = '1', 50);
  }, 500);
}

// 页面加载后启动动画
window.onload = () => {
  blinkCursor();
  type();
};

关键说明

  • 打字速度:通过typeInterval调整,数值越小打字越快,原CSS的2秒22字符对应约90ms的间隔
  • 光标闪烁:用blinkCursor函数模拟原CSS的blink动画,每500ms切换光标透明度
  • 过渡效果:通过opacity渐变实现平滑切换,避免生硬的显示/隐藏

内容的提问来源于stack exchange,提问作者Tom O'Hanlon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:01:13