Prevent page navigation on horizontal scroll

。_饼干妹妹 提交于 2020-07-06 08:36:33

问题


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



来源:https://stackoverflow.com/questions/50616221/prevent-page-navigation-on-horizontal-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!