xxm-test-js
Version:
xxm-js通用js工具(utils)库
75 lines • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectScrollDirection = detectScrollDirection;
/**
* 检测页面滚动方向。
* @returns {() => 'up' | 'down' | 'top' | 'bottom'} 返回一个函数,每次调用时返回当前的滚动方向。
* @example
* ```typescript
* // 使用示例
* // 在 Vue 2 组件中使用12-1
* export default {
* data() {
* return {
* scrollDirection: '' as 'up' | 'down' | 'top' | 'bottom'
* };
* },
* mounted() {
* const getScrollDirection = detectScrollDirection();
* window.addEventListener('scroll', () => {
* this.scrollDirection = getScrollDirection();
* console.log('当前滚动方向:', this.scrollDirection);
* });
* },
* beforeDestroy() {
* window.removeEventListener('scroll', this.handleScroll);
* }
* };
* ```
*/
function detectScrollDirection() {
// 存储最近几次滚动位置(用于计算趋势)
const positionHistory = [];
let lastDirection = 'top';
let lastStablePosition = window.pageYOffset;
// 初始化方向
if (lastStablePosition > 0) {
lastDirection = 'down';
}
return function () {
const currentPosition = window.pageYOffset;
positionHistory.push(currentPosition);
// 只保留最近 5 次滚动位置(用于计算趋势)
if (positionHistory.length > 5) {
positionHistory.shift();
}
// 1. 边界检测(顶部/底部)
if (currentPosition <= 0) {
lastDirection = 'top';
lastStablePosition = currentPosition;
return 'top';
}
if (currentPosition + window.innerHeight >= document.documentElement.scrollHeight - 1) {
lastDirection = 'bottom';
lastStablePosition = currentPosition;
return 'bottom';
}
// 2. 趋势分析(计算最近几次滚动的平均方向)
if (positionHistory.length >= 3) {
const oldestPos = positionHistory[0];
const newestPos = positionHistory[positionHistory.length - 1];
const avgDiff = (newestPos - oldestPos) / (positionHistory.length - 1);
// 只有当平均滚动趋势超过阈值(0.5px/次)才更新方向
if (Math.abs(avgDiff) > 0.5) {
const newDirection = avgDiff > 0 ? 'down' : 'up';
// 方向变化时,更新基准位置
if (newDirection !== lastDirection) {
lastStablePosition = currentPosition;
lastDirection = newDirection;
}
}
}
return lastDirection;
};
}
//# sourceMappingURL=detectScrollDirection.js.map