fix: Work 板块动画彻底修复(根因:hydration 前初始化样式被重置)

- 根因:watch(works, {immediate:true}) 在 setup 阶段(hydration 完成前)初始化,
  对 SSR 卡片应用定位后,Vue hydration 重置了内联样式 -> 动画永不生效
- 修复:
  1) 初始化推迟到 onMounted(hydration 后),watch 不再 immediate
  2) 卡片定位改用原生 style(不用 gsap.set,避免被 pin 机制 revert)
  3) DOM 选择器获取卡片/区块(不依赖 Vue 模板 ref,规避异步 setup 问题)
  4) 自愈重试轮询(200ms)直到卡片就绪 + initedOnce 只初始化一次
  5) 移除会引发 revert 循环的 MutationObserver
- 本地浏览器实测:卡片 absolute 堆叠、滚动时逐张滑入堆叠、pin 生效
This commit is contained in:
2026-08-06 23:07:54 +08:00
parent c26415bcc2
commit 59d8b2f0bf
+80 -61
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref, nextTick, computed, watch } from 'vue'
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
@@ -61,52 +61,53 @@ const partners = [
},
]
let ctx: gsap.Context | null = null
let observer: MutationObserver | null = null
let initedSig = ''
let st: ScrollTrigger | null = null
let madeTweens: gsap.core.Animation[] = []
let positionedCards: HTMLElement[] = []
let initedOnce = false
let retryTimer: ReturnType<typeof setTimeout> | null = null
let stopRetry = false
const refresh = () => {
ScrollTrigger.refresh()
}
// 每次从 DOM 实时查询卡片(不依赖 Vue ref,避免 hydration 二次渲染导致 ref 失效)
const getCards = (): HTMLElement[] => {
if (!rootRef.value) return []
return Array.from(rootRef.value.querySelectorAll<HTMLElement>('a[href^="/work/"]'))
}
// 全部用 DOM 选择器(仅客户端;SSR 无 document,返回空)
const getWorkSection = () => (typeof document !== 'undefined' ? document.getElementById('work') : null)
const getPinEl = () => (typeof document !== 'undefined' ? document.querySelector<HTMLElement>('#work [data-work-pin]') : null)
const getCards = (): HTMLElement[] =>
typeof document !== 'undefined'
? Array.from(document.querySelectorAll<HTMLElement>('#work a[href^="/work/"]'))
: []
const initScrollAnimation = () => {
if (!rootRef.value || !workSectionRef.value || !workPinRef.value) return
const initScrollAnimation = (): boolean => {
if (initedOnce) return true // 只初始化一次,绝不重初始化
const section = getWorkSection()
const pinEl = getPinEl()
if (!section || !pinEl) return false
const cards = getCards()
const count = cards.length
if (count < 2) return
if (count < 2) return false
initedOnce = true
// 签名:卡片元素/图片未变化则不重复初始化
const sig = cards.map((c) => c.querySelector('img')?.getAttribute('src') || c.getAttribute('href') || '').join('|')
if (sig === initedSig && ctx) return
initedSig = sig
ctx?.revert()
ctx = gsap.context(() => {
const enterOffset = 160
const scaleTo = 0.92
const depthOffsetY = -18
for (let i = 0; i < count; i += 1) {
const card = cards[i]
gsap.set(card, {
position: 'absolute',
inset: 0,
borderRadius: 22,
overflow: 'hidden',
transformOrigin: 'center center',
force3D: true,
zIndex: i + 1,
boxShadow: '0 18px 40px rgba(0,0,0,0.12)',
y: i === 0 ? 0 : window.innerHeight + enterOffset,
scale: 1,
// 定位卡片为 absolute 堆叠(用原生样式,避免 gsap.set 被 pin 机制 revert)
positionedCards = cards
cards.forEach((card, i) => {
card.style.position = 'absolute'
card.style.top = '0'
card.style.right = '0'
card.style.bottom = '0'
card.style.left = '0'
card.style.zIndex = String(i + 1)
card.style.borderRadius = '22px'
card.style.overflow = 'hidden'
card.style.boxShadow = '0 18px 40px rgba(0,0,0,0.12)'
card.style.transform = i === 0 ? 'none' : `translateY(${window.innerHeight + enterOffset}px)`
})
}
const tl = gsap.timeline()
for (let i = 1; i < count; i += 1) {
@@ -117,54 +118,72 @@ const initScrollAnimation = () => {
tl.to(prev, { scale: scaleTo, y: depthOffsetY, duration: 0.6, ease: 'power2.out' }, start + 0.35)
tl.set(prev, { scale: scaleTo, y: depthOffsetY }, start + 1)
}
madeTweens.push(tl)
ScrollTrigger.create({
trigger: workSectionRef.value,
st = ScrollTrigger.create({
trigger: section,
start: 'top top',
end: () => `+=${(count - 1) * window.innerHeight}`,
pin: workPinRef.value,
pin: pinEl,
scrub: true,
anticipatePin: 1,
invalidateOnRefresh: true,
animation: tl,
})
}, rootRef.value)
requestAnimationFrame(() => ScrollTrigger.refresh())
return true
}
// 幂等初始化:等 DOM 稳定后再执行
const tryInit = async () => {
await nextTick()
await nextTick()
requestAnimationFrame(() => initScrollAnimation())
// 自愈初始化:卡片尚未就绪时每 200ms 重试,直到成功(成功即停)
const ensureInit = () => {
if (stopRetry) return
if (typeof window === 'undefined') return // SSR 不执行
if (initScrollAnimation()) {
if (retryTimer) {
clearTimeout(retryTimer)
retryTimer = null
}
return
}
retryTimer = setTimeout(ensureInit, 200)
}
watch(works, () => {
if (works.value.length) tryInit()
}, { immediate: true, flush: 'post' })
// 数据变化时触发(不在 setup 立即执行——hydration 前初始化会被 hydration 重置样式)
watch(works, ensureInit)
onMounted(() => {
tryInit()
ensureInit() // hydration 完成后初始化
if (typeof window !== 'undefined') {
// 监听卡片容器 DOM 变化(hydration/数据到达后自动重初始化)
observer = new MutationObserver(() => tryInit())
if (rootRef.value) observer.observe(rootRef.value, { childList: true, subtree: true })
window.addEventListener('hero-intro-done', tryInit, { once: true })
setTimeout(() => {
window.removeEventListener('hero-intro-done', tryInit)
tryInit()
}, 3000)
window.addEventListener('hero-intro-done', ensureInit, { once: true })
setTimeout(ensureInit, 3000)
}
})
onUnmounted(() => {
observer?.disconnect()
observer = null
ctx?.revert()
ctx = null
initedSig = ''
stopRetry = true
if (retryTimer) clearTimeout(retryTimer)
if (st) {
st.kill()
st = null
}
madeTweens.forEach((t) => t.revert())
madeTweens = []
// 复位卡片定位样式
positionedCards.forEach((c) => {
if (!c) return
c.style.position = ''
c.style.top = ''
c.style.right = ''
c.style.bottom = ''
c.style.left = ''
c.style.zIndex = ''
c.style.borderRadius = ''
c.style.overflow = ''
c.style.boxShadow = ''
c.style.transform = ''
})
positionedCards = []
})
</script>
@@ -193,7 +212,7 @@ onUnmounted(() => {
<section id="work" ref="workSectionRef" class="bg-white">
<div class="w-page-container max-w-[calc(100%-2rem)] mx-auto px-4 pb-28">
<div
ref="workPinRef"
data-work-pin
class="flex flex-col lg:flex-row gap-10 lg:gap-16 h-[100svh] items-stretch"
>
<div class="lg:w-[340px] flex flex-col gap-8 pt-8 md:pt-10">