项目概况

GSAP动画示例

2026-01-291 min read前端技术
javascript

实现多屏幕,当某个屏幕中动画元素出现在视窗时候, 屏幕固定,开始动画。

  • scrub: true 表示滚动时动画同步
  • pin: true 表示动画时候,.ball-wrapper 改成 fixed
  • markers: true 表示显示标记
html
1<!DOCTYPE html> 2<html lang="en"> 3 4<head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8</head> 9 10<body> 11 <section></section> 12 <section class="ball-wrapper"> 13 <div class="ball"></div> 14 </section> 15 <section></section> 16</body> 17 18</html> 19<!-- GSAP --> 20<script src="https://unpkg.com/gsap/dist/gsap.min.js"></script> 21<script src="https://unpkg.com/gsap/dist/ScrollTrigger.min.js"></script> 22<script> 23 gsap.registerPlugin(ScrollTrigger); 24 25 // 动画对象是.ball 元素,触发动画对象是 .ball-wrapper滚动到 top 26 // scrub: true 表示滚动时动画同步 27 // markers: true 表示显示标记 28 // pin: true 表示动画时候,.ball-wrapper 改成 fixed 29 gsap.to('.ball', { 30 x: 900, 31 rotation: 360, 32 scale: 1.5, 33 backgroundColor: "red", 34 borderRadius: 150, 35 scrollTrigger: { 36 trigger: '.ball-wrapper', 37 pin: true, 38 scrub: true, 39 markers: true, 40 } 41 }); 42</script> 43<style> 44 body { 45 padding: 0; 46 margin: 0; 47 } 48 49 .ball { 50 width: 250px; 51 height: 250px; 52 background: #292424; 53 } 54 55 section { 56 width: 100vw; 57 height: 100vh; 58 display: flex; 59 align-items: center; 60 /* justify-content: center; */ 61 font-size: 40px; 62 font-weight: bold; 63 border: 1px solid red; 64 } 65 66 section:nth-child(1) { 67 background: #d8d8d8; 68 } 69 70 section:nth-child(2) { 71 background: #adaeaf; 72 } 73 74 section:nth-child(3) { 75 background: #595c5b; 76 } 77</style>