如何在不实际滚动的情况下确定滚动方向 [英] How to determine scroll direction without actually scrolling

查看:27
本文介绍了如何在不实际滚动的情况下确定滚动方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am coding a page where the first time the user scrolls, it doesn't actually scroll the page down, instead it adds a class with a transition. I'd like to detect when the user is scrolling down, because if he scrolls up, I want it to do something else. All the methods that I've found are based on defining the current body ScrollTop, and then comparing with the body scrollTop after the page scrolls, defining the direction, but since the page doesn't actually scroll, the body scrollTop() doesn't change.

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);

    }


});

这就是我带来的,但那样我滚动的方向并不重要,它会触发事件

This is what I have come with, but that way it doesn't matter the direction I scroll it triggers the event

推荐答案

mousewheel 事件很快就会过时.您应该改用 wheel 事件.

The mousewheel event is quickly becoming obsolete. You should use wheel event instead.

这也很容易让你在没有滚动条的情况下垂直和/或水平滚动.

This would also easily allow you to the vertical and/or horizontal scroll direction without scroll bars.

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

This event has support in all current major browsers and should remain the standard far into the future.

这是一个演示:

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>

这篇关于如何在不实际滚动的情况下确定滚动方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆