Files
ks-app-employment-service/hook/useScrollDirection.js

81 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2025-05-13 11:10:38 +08:00
import {
ref
} from 'vue'
export function useScrollDirection(options = {}) {
const {
2025-10-20 11:05:11 +08:00
threshold = 50, // 滚动偏移阈值,降低以更敏感
throttleTime = 16, // 节流时间毫秒约60fps
onChange = null, // 滚动方向变化的回调
hideThreshold = 100, // 隐藏区域的滚动阈值
enablePerformanceMode = true // 启用性能优化模式
2025-05-13 11:10:38 +08:00
} = options
const lastScrollTop = ref(0)
const accumulatedScroll = ref(0)
const isScrollingDown = ref(false)
2025-10-20 11:05:11 +08:00
const shouldHideTop = ref(false) // 控制顶部区域隐藏
const shouldStickyFilter = ref(false) // 控制筛选区域吸顶
2025-05-13 11:10:38 +08:00
let lastInvoke = 0
function handleScroll(e) {
const now = Date.now()
2025-10-20 11:05:11 +08:00
if (enablePerformanceMode && now - lastInvoke < throttleTime) return
2025-05-13 11:10:38 +08:00
lastInvoke = now
const scrollTop = e.detail.scrollTop
const delta = scrollTop - lastScrollTop.value
accumulatedScroll.value += delta
2025-10-20 11:05:11 +08:00
// 控制顶部区域隐藏
if (scrollTop > hideThreshold) {
if (!shouldHideTop.value) {
shouldHideTop.value = true
}
} else {
if (shouldHideTop.value) {
shouldHideTop.value = false
}
}
// 控制筛选区域吸顶(当顶部区域隐藏时)
if (scrollTop > hideThreshold + 50) { // 稍微延迟吸顶
if (!shouldStickyFilter.value) {
shouldStickyFilter.value = true
}
} else {
if (shouldStickyFilter.value) {
shouldStickyFilter.value = false
2025-05-13 11:10:38 +08:00
}
}
2025-10-20 11:05:11 +08:00
// 滚动方向检测(仅在性能模式下使用阈值)
if (!enablePerformanceMode || Math.abs(accumulatedScroll.value) > threshold) {
if (accumulatedScroll.value > 0) {
// 向下滚动
if (!isScrollingDown.value) {
isScrollingDown.value = true
onChange?.(true) // 通知变更为向下
}
} else {
// 向上滚动
if (isScrollingDown.value) {
isScrollingDown.value = false
onChange?.(false) // 通知变更为向上
}
}
if (enablePerformanceMode) {
accumulatedScroll.value = 0
2025-05-13 11:10:38 +08:00
}
}
lastScrollTop.value = scrollTop
}
return {
isScrollingDown,
2025-10-20 11:05:11 +08:00
shouldHideTop,
shouldStickyFilter,
2025-05-13 11:10:38 +08:00
handleScroll
}
}