Unable to preventDefault inside passive event listener due to target being treated as passive

一.需求: tab导航要求滚动效果

Unable to preventDefault inside passive event listener due to target being treated as passive_第1张图片

二.问题: iscroll左右滚动不流畅,

网上找了一通,大致有以下三种解决方法

方法一: 为滚动区域外层div添加下列css样式
  ```css
  #wrapper {
      touch-action: none;
  }
方法二: 添加disablePointer参数
new IScroll('#wrapper', {
    disablePointer: true
});
方法三: 为document对象的touchmove事件添加{passive: false}
document.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, {
    passive: false
});

结果不尽人意, 要么是滑动不顺畅问题没结局,要么是向下滑动加载内容时弹出以下报错

Unable to preventDefault inside passive event listener due to target being treated as passive....
https://www.chromestatus.com/features/5093566007214080

根据错误提示中的链接找到下列解释

AddEventListenerOptions defaults passive to false. With this change touchstart and touchmove listeners added to the document will default to passive:true (so that calls to preventDefault will be ignored)… If the value is explicitly provided in the AddEventListenerOptions it will continue having the value specified by the page. This is behind a flag starting in Chrome 54, and enabled by default in Chrome 56. See https://developers.google.com/web/updates/2017/01/scrolling-intervention

要了解上面的问题,我们先来看看addEventListener方法,实际上该方法是可接受第三个参数的,分别是capture, once, passive, 因此,下列写法是等价的

target.addEventListener(type, listener);
target.addEventListener(type, listener, false);
target.addEventListener(type, listener, {useCapture: false});

那passive参数是干嘛的呢?

passive: Boolean,表示 listener 永远不会调用 preventDefault()。如果 listener 仍然调用了这个函数,客户端将会忽略它并抛出一个控制台警告。

三. 最终解决方案, 在外面的wrapper上面使用e.preventDefault

 document.getElementById('scroller').addEventListener('touchmove',  function (e) { e.preventDefault(); }, { passive: false });

你可能感兴趣的:(javascript,踩坑汇总)