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

如何用Tailwind CSS实现网站Hero区的Animated Scrolling动态组件?

复刻Preline Hero区域滚动动画组件(Tailwind CSS实现)

组件名称

这类组件通常被称为滚动触发视口动画组件(Scroll-Triggered Viewport Animation Component),核心逻辑是当元素滚动进入浏览器视口范围时,触发预设的过渡动画(比如渐入、位移、缩放等),提升页面的交互层次感。

Tailwind CSS实现步骤

1. 自定义动画样式

在项目的样式文件中(或通过Tailwind配置扩展)添加动画关键帧和对应类:

@tailwind base;
@tailwind components;
@tailwind utilities;

/* 定义渐入上移动画 */
@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(30px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 动画触发类 */
.animate-fade-in-up {
  animation: fadeInUp 0.8s ease-out forwards;
}

/* 元素初始状态:隐藏待触发 */
.scroll-animate {
  opacity: 0;
  transform: translateY(30px);
}

2. 构建Hero区域HTML结构

使用Tailwind布局类搭建Hero内容,为需要动画的元素添加初始状态类:

<section class="min-h-screen flex items-center justify-center px-4 py-16 bg-gray-50">
  <div class="max-w-3xl text-center">
    <h1 class="scroll-animate text-4xl md:text-5xl font-bold text-gray-900 mb-6">Build better interfaces faster</h1>
    <p class="scroll-animate text-lg md:text-xl text-gray-600 mb-8">Preline UI is a set of prebuilt UI components based on Tailwind CSS that help you build modern websites faster.</p>
    <div class="scroll-animate flex flex-col sm:flex-row gap-4 justify-center">
      <button class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all">Get Started</button>
      <button class="px-6 py-3 bg-white text-gray-800 border border-gray-300 rounded-lg hover:bg-gray-50 transition-all">View Components</button>
    </div>
  </div>
</section>

3. 添加滚动触发逻辑

使用浏览器原生的IntersectionObserver API监听元素进入视口的事件,触发动画:

// 选中所有需要动画的元素
const animatedElements = document.querySelectorAll('.scroll-animate');

// 配置观察者参数
const observerConfig = {
  root: null, // 以视口为根容器
  rootMargin: '0px',
  threshold: 0.1 // 元素10%进入视口时触发动画
};

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('animate-fade-in-up');
      observer.unobserve(entry.target); // 动画触发后停止监听,避免重复触发
    }
  });
}, observerConfig);

// 为每个元素绑定观察者
animatedElements.forEach(el => observer.observe(el));

效果说明

上述实现完全复刻Preline Hero区域的滚动动画效果:页面滚动时,Hero区域的标题、描述、按钮会以渐入+上移的方式呈现,若需要元素依次动画,可给不同元素添加animation-delay自定义类实现 stagger 效果,动画流畅且符合现代UI交互规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:05:13