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"> <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 { useI18n } from 'vue-i18n'
import gsap from 'gsap' import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger' import { ScrollTrigger } from 'gsap/ScrollTrigger'
@@ -61,52 +61,53 @@ const partners = [
}, },
] ]
let ctx: gsap.Context | null = null let st: ScrollTrigger | null = null
let observer: MutationObserver | null = null let madeTweens: gsap.core.Animation[] = []
let initedSig = '' let positionedCards: HTMLElement[] = []
let initedOnce = false
let retryTimer: ReturnType<typeof setTimeout> | null = null
let stopRetry = false
const refresh = () => { const refresh = () => {
ScrollTrigger.refresh() ScrollTrigger.refresh()
} }
// 每次从 DOM 实时查询卡片(不依赖 Vue ref,避免 hydration 二次渲染导致 ref 失效) // 全部用 DOM 选择器(仅客户端;SSR 无 document,返回空)
const getCards = (): HTMLElement[] => { const getWorkSection = () => (typeof document !== 'undefined' ? document.getElementById('work') : null)
if (!rootRef.value) return [] const getPinEl = () => (typeof document !== 'undefined' ? document.querySelector<HTMLElement>('#work [data-work-pin]') : null)
return Array.from(rootRef.value.querySelectorAll<HTMLElement>('a[href^="/work/"]')) const getCards = (): HTMLElement[] =>
} typeof document !== 'undefined'
? Array.from(document.querySelectorAll<HTMLElement>('#work a[href^="/work/"]'))
: []
const initScrollAnimation = () => { const initScrollAnimation = (): boolean => {
if (!rootRef.value || !workSectionRef.value || !workPinRef.value) return if (initedOnce) return true // 只初始化一次,绝不重初始化
const section = getWorkSection()
const pinEl = getPinEl()
if (!section || !pinEl) return false
const cards = getCards() const cards = getCards()
const count = cards.length 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 enterOffset = 160
const scaleTo = 0.92 const scaleTo = 0.92
const depthOffsetY = -18 const depthOffsetY = -18
for (let i = 0; i < count; i += 1) { // 定位卡片为 absolute 堆叠(用原生样式,避免 gsap.set 被 pin 机制 revert)
const card = cards[i] positionedCards = cards
gsap.set(card, { cards.forEach((card, i) => {
position: 'absolute', card.style.position = 'absolute'
inset: 0, card.style.top = '0'
borderRadius: 22, card.style.right = '0'
overflow: 'hidden', card.style.bottom = '0'
transformOrigin: 'center center', card.style.left = '0'
force3D: true, card.style.zIndex = String(i + 1)
zIndex: i + 1, card.style.borderRadius = '22px'
boxShadow: '0 18px 40px rgba(0,0,0,0.12)', card.style.overflow = 'hidden'
y: i === 0 ? 0 : window.innerHeight + enterOffset, card.style.boxShadow = '0 18px 40px rgba(0,0,0,0.12)'
scale: 1, card.style.transform = i === 0 ? 'none' : `translateY(${window.innerHeight + enterOffset}px)`
}) })
}
const tl = gsap.timeline() const tl = gsap.timeline()
for (let i = 1; i < count; i += 1) { 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.to(prev, { scale: scaleTo, y: depthOffsetY, duration: 0.6, ease: 'power2.out' }, start + 0.35)
tl.set(prev, { scale: scaleTo, y: depthOffsetY }, start + 1) tl.set(prev, { scale: scaleTo, y: depthOffsetY }, start + 1)
} }
madeTweens.push(tl)
ScrollTrigger.create({ st = ScrollTrigger.create({
trigger: workSectionRef.value, trigger: section,
start: 'top top', start: 'top top',
end: () => `+=${(count - 1) * window.innerHeight}`, end: () => `+=${(count - 1) * window.innerHeight}`,
pin: workPinRef.value, pin: pinEl,
scrub: true, scrub: true,
anticipatePin: 1, anticipatePin: 1,
invalidateOnRefresh: true, invalidateOnRefresh: true,
animation: tl, animation: tl,
}) })
}, rootRef.value)
requestAnimationFrame(() => ScrollTrigger.refresh()) requestAnimationFrame(() => ScrollTrigger.refresh())
return true
} }
// 幂等初始化:等 DOM 稳定后再执行 // 自愈初始化:卡片尚未就绪时每 200ms 重试,直到成功(成功即停)
const tryInit = async () => { const ensureInit = () => {
await nextTick() if (stopRetry) return
await nextTick() if (typeof window === 'undefined') return // SSR 不执行
requestAnimationFrame(() => initScrollAnimation()) if (initScrollAnimation()) {
if (retryTimer) {
clearTimeout(retryTimer)
retryTimer = null
}
return
}
retryTimer = setTimeout(ensureInit, 200)
} }
watch(works, () => { // 数据变化时触发(不在 setup 立即执行——hydration 前初始化会被 hydration 重置样式)
if (works.value.length) tryInit() watch(works, ensureInit)
}, { immediate: true, flush: 'post' })
onMounted(() => { onMounted(() => {
tryInit() ensureInit() // hydration 完成后初始化
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// 监听卡片容器 DOM 变化(hydration/数据到达后自动重初始化) window.addEventListener('hero-intro-done', ensureInit, { once: true })
observer = new MutationObserver(() => tryInit()) setTimeout(ensureInit, 3000)
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)
} }
}) })
onUnmounted(() => { onUnmounted(() => {
observer?.disconnect() stopRetry = true
observer = null if (retryTimer) clearTimeout(retryTimer)
ctx?.revert() if (st) {
ctx = null st.kill()
initedSig = '' 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> </script>
@@ -193,7 +212,7 @@ onUnmounted(() => {
<section id="work" ref="workSectionRef" class="bg-white"> <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 class="w-page-container max-w-[calc(100%-2rem)] mx-auto px-4 pb-28">
<div <div
ref="workPinRef" data-work-pin
class="flex flex-col lg:flex-row gap-10 lg:gap-16 h-[100svh] items-stretch" 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"> <div class="lg:w-[340px] flex flex-col gap-8 pt-8 md:pt-10">