是否有一个javascript事件侦听器只在用户向上滚动时检测,或者只在用户向下滚动时检测

Is there a javascript event listener that detects only when the user scrolls up, or only when the user scrolls down?

本文关键字:滚动 检测 用户 或者 有一个 事件 是否 侦听器 javascript      更新时间:2023-09-26

我知道。scroll()检测到滚动,但如果我只想在用户向下滚动时发生什么,或者反之亦然,该怎么办?

没有监听器,但您可以滚动最后一个位置的变量,并对照新的位置进行检查。所以它应该是这样的:

保留一个变量,比如last_scroll_position,当你有一个滚动时,如果last_scroll_position - current_position > 0,用户会向上滚动,如果小于0,用户会向下滚动。

供进一步参考:

区分jquery中的向上/向下滚动?

示例:

<div style='height:10000px;'>
var last_scroll=0;
$(window).scroll(function() {
    var direction='none';
    var current_scroll=$(this).scrollTop();
    if(current_scroll < last_scroll) direction='up';
    else if(current_scroll > last_scroll) direction = 'down';
    last_scroll=current_scroll;
    console.log(direction)
});