Communitygithub.com

ComeOnOliver/skillshub

GSAP 动画最佳实践,涵盖滚动触发、性能优化、无障碍、响应式动画和测试集成。在 WordPress 或任何 Web 项目上实现或审查动画时使用。

skillshub 是什么?

本技能为使用 GSAP(GreenSock Animation Platform)实施专业、可访问且高性能的动画提供全面指南。它涵盖了核心原则,例如优先使用 GPU 加速的 `transform` 和 `opacity` 属性、尊重用户的 `prefers-reduced-motion` 设置以及采用渐进增强策略。技能详细介绍了 GSAP 和 ScrollTrigger 插件的安装方法(包括 CDN 链接和 WordPress 入队代码),并提供了多种动画模式示例,如滚动淡入、元素交错、视差效果、文本逐行揭示和帷幕遮罩揭示。此外,还深入讨论了响应式动画(使用 gsap.matchMedia)、性能优化(批处理相似动画、清理未使用的触发器)和 ScrollTrigger 最佳实践。该技能还包含了与视觉 QA 和 Playwright 测试集成的代码,以及一个可复用的 JavaScript 动画库,通过 `data-` 属性方便地在 HTML 中使用。最后,提供了一个发布前检查清单和调试技巧。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/crazyswami/gsap-animations

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

预览

来自技能 README

skillshub preview

文档

GSAP 动画最佳实践

使用 GSAP(GreenSock Animation Platform)实施专业、可访问且高性能动画的全面指南。

核心原则

1. 性能优先

  • 仅对 transform 和 opacity 进行动画处理(GPU 加速)
  • 避免对 width、height、top、left、margin、padding 进行动画处理
  • 谨慎使用 will-change
  • 在所有设备上目标达到 60fps

2. 无障碍始终

  • 尊重 prefers-reduced-motion
  • 确保内容在没有 JavaScript 的情况下可见
  • 不要将关键内容隐藏在动画后面
  • 为长时间动画提供跳过/暂停控件

3. 渐进增强

  • 内容必须在没有动画的情况下正常工作
  • 动画增强功能,而非替代功能
  • 在禁用动画的情况下进行测试

GSAP 设置

安装

<!-- CDN(推荐用于 WordPress) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>

<!-- 可选插件 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollSmoother.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/SplitText.min.js"></script>

WordPress 入队

function theme_enqueue_gsap() {
    // GSAP 核心
    wp_enqueue_script(
        'gsap',
        'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js',
        array(),
        '3.12.5',
        true
    );

    // ScrollTrigger
    wp_enqueue_script(
        'gsap-scrolltrigger',
        'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js',
        array('gsap'),
        '3.12.5',
        true
    );

    // 主题动画
    wp_enqueue_script(
        'theme-animations',
        get_theme_file_uri('/assets/js/animations.js'),
        array('gsap', 'gsap-scrolltrigger'),
        filemtime(get_theme_file_path('/assets/js/animations.js')),
        true
    );
}
add_action('wp_enqueue_scripts', 'theme_enqueue_gsap');

动画模式

1. 滚动淡入

// 基本淡入
gsap.from('.fade-in', {
    opacity: 0,
    y: 50,
    duration: 1,
    stagger: 0.2,
    scrollTrigger: {
        trigger: '.fade-in',
        start: 'top 80%',
        toggleActions: 'play none none none'
    }
});

2. 交错元素

// 卡片逐个出现
gsap.from('.card', {
    opacity: 0,
    y: 100,
    duration: 0.8,
    stagger: {
        amount: 0.6,
        from: 'start'
    },
    ease: 'power2.out',
    scrollTrigger: {
        trigger: '.cards-container',
        start: 'top 75%'
    }
});

3. 视差效果

// 图像上的微妙视差
gsap.to('.parallax-image', {
    yPercent: -20,
    ease: 'none',
    scrollTrigger: {
        trigger: '.parallax-section',
        start: 'top bottom',
        end: 'bottom top',
        scrub: true
    }
});

4. 文本逐行揭示

// 需要 SplitText 插件(Club GreenSock)
// 或使用以下基于 CSS 的替代方案

// CSS 替代方案 - 将每行包裹在 span 中
gsap.from('.reveal-line', {
    opacity: 0,
    y: '100%',
    duration: 0.8,
    stagger: 0.1,
    ease: 'power3.out',
    scrollTrigger: {
        trigger: '.text-reveal',
        start: 'top 80%'
    }
});

5. 帷幕/遮罩揭示

// 通过滑动遮罩揭示图像
gsap.to('.curtain-mask', {
    scaleX: 0,
    transformOrigin: 'right center',
    duration: 1.2,
    ease: 'power4.inOut',
    scrollTrigger: {
        trigger: '.curtain-container',
        start: 'top 70%'
    }
});

6. Hero 动画时间线

// 复杂 hero 序列
const heroTL = gsap.timeline({
    defaults: { ease: 'power3.out' }
});

heroTL
    .from('.hero-bg', { scale: 1.2, duration: 1.5 })
    .from('.hero-title', { opacity: 0, y: 100, duration: 1 }, '-=1')
    .from('.hero-subtitle', { opacity: 0, y: 50, duration: 0.8 }, '-=0.5')
    .from('.hero-cta', { opacity: 0, y: 30, duration: 0.6 }, '-=0.3');

无障碍

尊重减少动效

// 检查用户偏好
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

// 选项 1:禁用所有动画
if (prefersReducedMotion) {
    gsap.globalTimeline.timeScale(0);
    ScrollTrigger.getAll().forEach(st => st.kill());
}

// 选项 2:简化动画
const animationConfig = prefersReducedMotion
    ? { duration: 0, stagger: 0 }
    : { duration: 1, stagger: 0.2 };

gsap.from('.element', {
    opacity: 0,
    y: prefersReducedMotion ? 0 : 50,
    ...animationConfig
});

CSS 回退

/* 确保内容在没有 JS 的情况下可见 */
.fade-in {
    opacity: 1;
    transform: translateY(0);
}

/* 仅当动画运行时隐藏 */
.js .fade-in {
    opacity: 0;
    transform: translateY(50px);
}

/* 在 CSS 中也尊重减少动效 */
@media (prefers-reduced-motion: reduce) {
    .js .fade-in {
        opacity: 1;
        transform: none;
    }
}

向 HTML 添加 JS 类

// 在脚本开头添加
document.documentElement.classList.add('js');

响应式动画

断点感知动画

// 创建响应式动画
const mm = gsap.matchMedia();

mm.add('(min-width: 1024px)', () => {
    // 桌面端动画
    gsap.from('.hero-image', {
        x: 100,
        opacity: 0,
        duration: 1.2
    });

    return () => {
        // 断点更改时清理
    };
});

mm.add('(max-width: 1023px)', () => {
    // 移动端动画(更简单)
    gsap.from('.hero-image', {
        opacity: 0,
        duration: 0.8
    });
});

在调整大小时刷新

// 在调整大小时重新计算 ScrollTrigger
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        ScrollTrigger.refresh();
    }, 250);
});

性能优化

1. 仅使用 Transform 属性

// 好 - GPU 加速
gsap.to('.element', {
    x: 100,          // transform: translateX
    y: 50,           // transform: translateY
    rotation: 45,    // transform: rotate
    scale: 1.2,      // transform: scale
    opacity: 0.5
});

// 差 - 导致布局/绘制
gsap.to('.element', {
    left: 100,       // 触发布局
    width: '200px',  // 触发布局
    marginTop: 50    // 触发布局
});

2. 批处理相似动画

// 对许多相似元素使用 batch
ScrollTrigger.batch('.card', {
    onEnter: batch => gsap.to(batch, {
        opacity: 1,
        y: 0,
        stagger: 0.1
    }),
    start: 'top 85%'
});

3. 杀死未使用的 ScrollTrigger

// 导航(SPA)或组件卸载时清理
function cleanup() {
    ScrollTrigger.getAll().forEach(st => st.kill());
    gsap.killTweensOf('*');
}

4. 惰性初始化

// 仅对可见部分初始化动画
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            initSectionAnimations(entry.target);
            observer.unobserve(entry.target);
        }
    });
}, { rootMargin: '100px' });

document.querySelectorAll('.animated-section').forEach(section => {
    observer.observe(section);
});

ScrollTrigger 最佳实践

1. 正确的开始/结束点

// 避免常见错误
ScrollTrigger.create({
    trigger: '.section',
    start: 'top 80%',    // 当触发器顶部到达视口顶部 80% 时
    end: 'bottom 20%',   // 当触发器底部到达顶部 20% 时
    markers: true,       // 仅用于调试 - 生产环境移除!
});

2. 谨慎固定部分

// 固定可能导致布局问题
ScrollTrigger.create({
    trigger: '.pinned-section',
    start: 'top top',
    end: '+=100%',
    pin: true,
    pinSpacing: true,    // 通常希望为 true
    anticipatePin: 1     // 有助于移动端
});

3. 处理图像加载

// 等待图像加载后再计算位置
ScrollTrigger.config({
    ignoreMobileResize: true
});

window.addEventListener('load', () => {
    ScrollTrigger.refresh();
});

// 或在懒加载图像后刷新
document.querySelectorAll('img[loading="lazy"]').forEach(img => {
    img.addEventListener('load', () => ScrollTrigger.refresh());
});

测试集成

视觉 QA 兼容性

为了让 visual-qa 技能正确捕获动画:

// 暴露函数以立即完成所有动画
window.completeAllAnimations = function() {
    gsap.globalTimeline.progress(1);
    ScrollTrigger.getAll().forEach(st => {
        st.scroll(st.end);
    });
};

// 或完全跳过截图动画
if (window.location.search.includes('skip-animations')) {
    gsap.globalTimeline.timeScale(100);
}

Playwright 测试

// 在 Playwright 测试中
await page.evaluate(() => {
    if (window.completeAllAnimations) {
        window.completeAllAnimations();
    }
});
await page.waitForTimeout(500);
await page.screenshot({ path: 'screenshot.png', fullPage: true });

通用动画库

可复用的动画类

// animations.js - 可复用的动画库

const Animations = {
    // 初始化所有动画
    init() {
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            return;
        }

        this.fadeIn();
        this.slideIn();
        this.parallax();
        this.textReveal();
    },

    fadeIn() {
        gsap.utils.toArray('[data-animate="fade-in"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                y: 50,
                duration: 0.8,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 85%',
                    once: true
                }
            });
        });
    },

    slideIn() {
        gsap.utils.toArray('[data-animate="slide-left"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                x: -100,
                duration: 1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });

        gsap.utils.toArray('[data-animate="slide-right"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                x: 100,
                duration: 1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });
    },

    parallax() {
        gsap.utils.toArray('[data-parallax]').forEach(el => {
            const speed = el.dataset.parallax || 0.2;
            gsap.to(el, {
                yPercent: -100 * speed,
                ease: 'none',
                scrollTrigger: {
                    trigger: el.parentElement,
                    start: 'top bottom',
                    end: 'bottom top',
                    scrub: true
                }
            });
        });
    },

    textReveal() {
        gsap.utils.toArray('[data-animate="text-reveal"]').forEach(el => {
            const lines = el.querySelectorAll('.line');
            gsap.from(lines, {
                opacity: 0,
                y: '100%',
                duration: 0.8,
                stagger: 0.1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });
    },

    // 动态内容后刷新
    refresh() {
        ScrollTrigger.refresh();
    },

    // SPA 导航时清理
    destroy() {
        ScrollTrigger.getAll().forEach(st => st.kill());
        gsap.killTweensOf('*');
    }
};

// DOM 就绪时初始化
document.addEventListener('DOMContentLoaded', () => Animations.init());

HTML 用法

<!-- 淡入 -->
<div data-animate="fade-in">内容</div>

<!-- 从左侧滑入 -->
<div data-animate="slide-left">内容</div>

<!-- 视差(0.2 = 20% 速度) -->
<img data-parallax="0.3" src="image.jpg">

<!-- 文本揭示(需要行包裹) -->
<div data-animate="text-reveal">
    <div class="line">第一行</div>
    <div class="line">第二行</div>
</div>

调试

启用标记

ScrollTrigger.defaults({
    markers: true  // 显示开始/结束标记
});

记录动画事件

gsap.to('.element', {
    x: 100,
    onStart: () => console.log('动画已开始'),
    onComplete: () => console.log('动画已完成'),
    onUpdate: self => console.log('进度:', self.progress())
});

检查问题

// 列出所有 ScrollTrigger
console.log('ScrollTriggers:', ScrollTrigger.getAll());

// 检查元素是否存在
const el = document.querySelector('.animated-element');
if (!el) console.warn('动画目标未找到!');

检查清单

发布前

  • 移除所有 markers: true
  • 使用 prefers-reduced-motion: reduce 测试
  • 在移动设备上测试(真实设备,而不仅仅是 DevTools)
  • 在 DevTools Performance 标签中检查性能
  • 在目标设备上验证 60fps
  • 内容在没有 JavaScript 的情况下可见
  • 在 ScrollTrigger 刷新前图像已懒加载
  • 无布局抖动(避免对布局属性进行动画处理)

视觉 QA 集成

  • 动画在截图前完成
  • 全页滚动触发所有动画
  • 截图捕获最终动画状态
  • 在所有视口尺寸下测试

资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能