Files
company-site/hooks/use-parallax.ts
JanYork 6a68a96287 feat: 添加连锁门店系统首页及核心UI组件
新增首页布局、导航栏、页脚及多个核心UI组件(按钮、卡片、表格等)
添加图片资源、工具函数和样式配置
实现响应式设计和主题支持
包含行业解决方案展示区块
2026-03-18 10:50:42 +08:00

49 lines
1.4 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client"
import { useState, useEffect, useRef, useCallback } from "react"
/**
* 监听滚动位置,返回 scrollY 值(被动监听,高性能)
*/
export function useScrollY() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const onScroll = () => setScrollY(window.scrollY)
window.addEventListener("scroll", onScroll, { passive: true })
return () => window.removeEventListener("scroll", onScroll)
}, [])
return scrollY
}
/**
* 对给定元素计算视差偏移量
* @param speed 视差倍率0 = 无效果0.5 = 半速(向上),负值反向
* @returns ref + translateY 字符串
*/
export function useParallax(speed: number = 0.4) {
const ref = useRef<HTMLDivElement>(null)
const [offset, setOffset] = useState(0)
const calculate = useCallback(() => {
if (!ref.current) return
const rect = ref.current.getBoundingClientRect()
const centerY = rect.top + rect.height / 2
const viewportCenter = window.innerHeight / 2
setOffset((centerY - viewportCenter) * speed)
}, [speed])
useEffect(() => {
calculate()
window.addEventListener("scroll", calculate, { passive: true })
window.addEventListener("resize", calculate, { passive: true })
return () => {
window.removeEventListener("scroll", calculate)
window.removeEventListener("resize", calculate)
}
}, [calculate])
return { ref, translateY: `${offset}px` }
}