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

HTML/CSS动画场景下设置h2文本动效无法生效问题求解

h2文本动画效果实现方案

你当前使用的是Astro框架搭建的站点,按照以下步骤可快速实现h2动画效果:

  • 第一步:给需要添加动画的h2元素添加自定义类名,比如animated-heading,方便样式选择器匹配
  • 第二步:根据需求选择对应的动画实现方案,以下是两种常用的无第三方依赖实现:

方案1:滚动触发展示的淡入上移动画

先在全局样式文件(路径为src/styles/global.css)中添加基础样式:

.animated-heading {
  opacity: 0;
  transform: translateY(30px);
  transition: all 0.8s cubic-bezier(0.22, 1, 0.36, 1);
}

.animated-heading.animate {
  opacity: 1;
  transform: translateY(0);
}

再在页面公共布局文件的<script>标签中添加监听逻辑,实现滚动到h2位置才触发动画:

const headingObserver = new IntersectionObserver((entries) => {
  entries.forEach(item => {
    if (item.isIntersecting) {
      item.target.classList.add('animate')
      headingObserver.unobserve(item.target)
    }
  })
}, {
  threshold: 0.6 // 元素露出60%时触发动画,可自行调整
})

document.querySelectorAll('.animated-heading').forEach(el => {
  headingObserver.observe(el)
})

方案2:自动触发的打字机动画

适合短标题场景,直接在全局样式中添加如下代码即可:

.animated-heading {
  width: fit-content;
  overflow: hidden;
  border-right: 3px solid #ffffff; /* 光标颜色可根据站点主题调整 */
  white-space: nowrap;
  animation: typing 3s steps(18, end) forwards, cursorBlink 0.8s step-end infinite;
}

@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

@keyframes cursorBlink {
  0%, 100% {
    border-color: transparent;
  }
  50% {
    border-color: #ffffff;
  }
}
  • 第三步:修改完成后执行npm run build构建项目后部署即可生效

注意如果你的h2写在React/Vue等客户端组件内,直接给组件内的h2添加对应类名即可,样式可以写在组件的局部样式块中,无需调整逻辑。


内容的提问来源于stack exchange,提问作者Irtiza Khan Labib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:24:06