防止水平滚动页面导航

Pra*_*Rkv 10 javascript scroll trackpad mousewheel gestures

我正在使用mac触控板.如何防止页面返回和在水平滚动上访问过的页面旁边?

我试图阻止车轮事件,但它在大多数情况下都不起作用.

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

即使我尝试阻止鼠标滚轮事件,这也导致页面导航.

Cha*_*row 13

您可以使用 CSS 来做到这一点。

html {
  overscroll-behavior-x: contain;
}
Run Code Online (Sandbox Code Playgroud)

此处记录了 Chrome 的情况。

包含- 防止滚动链接。卷轴不会传播到祖先,但会显示节点内的局部效果。例如,Android 上的过度滚动发光效果或 iOS 上的橡皮筋效果,当用户到达滚动边界时会通知用户。注意:在 html 元素上使用 overscroll-behavior: contains 可防止过度滚动导航操作。

在 chrome 版本 77 OSX 上测试

注意:这仍然是一个非标准 CSS 属性:https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior


Mac*_*was 11

它与网页及其事件无关,这是特定的系统行为,我认为它不能从javascript级别被阻止.

如果要禁用它 - 请转到:Apple Logo > Preferences > Trackpad > More gestures并取消选中Swipe between pages

//编辑

好吧,我google了一下,似乎我错了 - 一个解决方案,基本上很简单:

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);
Run Code Online (Sandbox Code Playgroud)

刚刚在OSX Chrome 67上测试了这个