-->

Prevent page navigation on horizontal scroll

2020-08-13 08:02发布

问题:

I am using a mac trackpad.How to prevent the page going back and next to visited pages on horizontal scroll ?.

I tried to prevent the wheel events but it doesn't works most of the time.

container.addEventListener('wheel', function(ev) {
    ev.preventDefault();
    ev.stopPropagation();
    return false;
}, {passive: false, capture: true});

even I tried blocking with mousewheel event which also leads to page navigation.

回答1:

It has nothing to do with a webpage nor its events; this is specific system behavior and I don't think it can be blocked from javascript level.

If you want to disable it - go to: Apple Logo > Preferences > Trackpad > More gestures and uncheck Swipe between pages

// EDIT

Ok, I googled a bit and it seems I was wrong- there is a solution to that and basically is pretty simple:

document.body.addEventListener('mousewheel', function(e) {
  e.stopPropagation();
  var max = this.scrollWidth - this.offsetWidth; // this might change if you have dynamic content, perhaps some mutation observer will be useful here

  if (this.scrollLeft + e.deltaX < 0 || this.scrollLeft + e.deltaX > max) {
    e.preventDefault();
    this.scrollLeft = Math.max(0, Math.min(max, this.scrollLeft + e.deltaX));
  }
}, false);

Just tested this on OSX Chrome 67



回答2:

You can do this with CSS.

html {
  overscroll-behavior-x: contain;
}

Documented for Chrome here.

contain - prevents scroll chaining. Scrolls do not propagate to ancestors but local effects within the node are shown. For example, the overscroll glow effect on Android or the rubberbanding effect on iOS which notifies the user when they've hit a scroll boundary. Note: using overscroll-behavior: contain on the html element prevents overscroll navigation actions.

Tested on chrome version 77 OSX

Note: This is still a non-standard CSS property: https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior