Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - How to determine scroll direction without actually scrolling

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Here is a demo:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...