如何确定滚动方向,而不实际滚动

How to determine scroll direction without actually scrolling

本文关键字:滚动 不实际 方向 何确定      更新时间:2023-09-26

我正在编写一个页面,其中用户第一次滚动时,它实际上并没有向下滚动页面,而是添加了一个带过渡的类。我想检测用户什么时候在向下滚动,因为如果他向上滚动,我想让它做别的事情。我发现的所有方法都是基于定义当前body ScrollTop,然后在页面滚动后与body ScrollTop进行比较,定义方向,但由于页面实际上并不滚动,body ScrollTop()不会改变。

animationIsDone = false;
function preventScroll(e) {
    e.preventDefault();
    e.stopPropagation();
}
$('body').on('mousewheel', function(e) {
    if (animationIsDone === false) {
        $("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker");
        $(".site-info").first().addClass("is-description-visible");
        preventScroll(e);
        setTimeout(function() {
            animationIsDone = true;
        }, 1000);
    }

});

这就是我想要的,但是这样不管我滚动的方向它都会触发事件

mousewheel事件正在迅速过时。您应该使用wheel事件。

这也可以很容易地让你在没有滚动条的情况下进行垂直和/或水平滚动。

当前所有主流浏览器都支持此事件,并将在未来很长一段时间内保持标准。

下面是一个示例:

window.addEventListener('wheel', function(event)
{
 if (event.deltaY < 0)
 {
  console.log('scrolling up');
  document.getElementById('status').textContent= 'scrolling up';
 }
 else if (event.deltaY > 0)
 {
  console.log('scrolling down');
  document.getElementById('status').textContent= 'scrolling down';
 }
});
<div id="status"></div>

addEventListener试试

window.addEventListener('mousewheel', function(e){
    wDelta = e.wheelDelta < 0 ? 'down' : 'up';
    console.log(wDelta);
});

演示

更新:

正如在其中一个答案中提到的,mousewheel事件被折旧了。你应该使用wheel事件。

我知道这篇文章是5年前的,但我没有看到任何好的Jquery答案(.on('mousewheel')不适合我…)

使用jquery的简单答案,并使用窗口而不是主体,以确保您正在使用滚动事件:

$(window).on('wheel', function(e) {
    var scroll = e.originalEvent.deltaY < 0 ? 'up' : 'down';
    console.log(scroll);
});

尝试使用e.wheelDelta

var animationIsDone = false, scrollDirection = 0;
function preventScroll(e) {
    e.preventDefault();
    e.stopPropagation();
}
$('body').on('mousewheel', function(e) {
    if (e.wheelDelta >= 0) {
        console.log('Scroll up'); //your scroll data here
    }
    else {
        console.log('Scroll down'); //your scroll data here
    }
    if (animationIsDone === false) {
        $("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker");
        $(".site-info").first().addClass("is-description-visible");
        preventScroll(e);
        setTimeout(function() {
            animationIsDone = true;
        }, 1000);
    }

});

注意:记住MouseWheel已被弃用,FireFox中不支持

这个在react app中起作用

<p onWheel={this.onMouseWheel}></p> 

添加事件监听器后,在函数u中可以使用deltaY捕获鼠标滚轮

onMouseWheel = (e) => {
 e.deltaY > 0 
   ? console.log("Down")
   : console.log("up")
}

chrome和

$('body').on('mousewheel', function(e) {
    if (e.originalEvent.deltaY >= 0) {
        console.log('Scroll up'); //your scroll data here
    }
    else {
        console.log('Scroll down'); //your scroll data here
    }
});