JQuery / JS : Detect user's scroll attempt wit

2019-02-12 18:07发布

I'm working on a transitioning website, and while I want to use the user's scroll attempt as the transition initiator, I don't want there to be a window scroll bar.

Right now, I'm simply detecting that the user scrolls (I've made my window size 1px taller that the user's screen for a scrollbar, although this is what I'm trying to avoid) with jquery's

.scroll(function)

method, and using that to transition my page, but I'd like to detect the user's scroll attempt without having to make my page overflow by a pixel, and thus showing the scrollbar

How can this be done?

Messy patch possibility that I know of:

Positioning the window inside an outer wrapper and hiding the scrollbar in the overflow of the wrapper. This is a patch up job and not a solution. It results in the page content being off-center since not all browsers use the same width for their scrollbars.

3条回答
等我变得足够好
2楼-- · 2019-02-12 18:25

Have a look at this question. I used it as a reference to make this fiddle.

Works only in Firefox:

$('html').on ('DOMMouseScroll', function (e) {
    var delta = e.originalEvent.detail;

    if (delta < 0) {
        $('p').text ('You scrolled up');
    } else if (delta > 0) {
        $('p').text ('You scrolled down');
    }

});

Works in Chrome, IE, Opera and Safari:

$('html').on ('mousewheel', function (e) {
    var delta = e.originalEvent.wheelDelta;

    if (delta < 0) {
        $('p').text ('You scrolled down');
    } else if (delta > 0) {
        $('p').text ('You scrolled up');
    }
});

You'd have to bind it on an element that spans your entire browser screen.

查看更多
ら.Afraid
3楼-- · 2019-02-12 18:34

The modern solution relies on the wheel event (IE9+)

$('selector').on('wheel', function(event) {
  var delta = {
    x: event.originalEvent.deltaX, 
    y: event.originalEvent.deltaY
  };

  if (delta.x != 0 || delta.y != 0) {
    //user scrolled
  }
});
查看更多
爷的心禁止访问
4楼-- · 2019-02-12 18:41

The answer from TreeTree can be simplified into one function that supports all browsers. Combine the mousewheel and DOMMouseScroll events since jQuery supports one or more event parameter(s). However, my testing showed on() did not work in the latest Firefox. Use bind() instead. You can also combine the var delta declaration to support all browsers:

$('html').bind('mousewheel DOMMouseScroll', function (e) {
    var delta = (e.originalEvent.wheelDelta || -e.originalEvent.detail);

    if (delta < 0) {
        console.log('You scrolled down');
    } else if (delta > 0) {
        console.log('You scrolled up');
    }
});
查看更多
登录 后发表回答