控制台报错:[Intervention]Unable to preventDefault inside passive event listener due..

369 阅读1分钟

控制台报错:[Intervention]Unable to preventDefault inside passive event listener due to target being treated as passive.

1 错误信息

在这里插入图片描述

2 报错原因

chrome 为了提高页面的滑动流畅度,从 chrome 5、6 开始,在 window、document 和 body 上注册的 touchstart 和 touchmove 事件处理函数,会默认为是 passive: true。

3 解决方法

方法1:注册处理函数时,用如下方式,明确声明为不是被动的。

window.addEventListener('touchmove', func, { passive: false })

方法2:应用 CSS 属性 touch-action: none; 这样任何触摸事件都不会产生默认行为,但是 touch 事件照样触发。例如:使用全局样式样式去掉默认行为。

* {
  touch-action: none;
}

4 touch-action 属性

CSS 属性 touch-action 用于设置触摸屏用户如何操纵元素的区域 (例如,浏览器内置的缩放功能)。可选值如下:

/* 当触控事件发生在元素上时,由浏览器来决定进行哪些操作,比如对 viewport 进行平滑、缩放等。*/
touch-action: auto;

/* 当触控事件发生在元素上时,不进行任何操作。*/
touch-action: none;

/* 启用单指水平平移手势。可以与 pan-y 、pan-up、pan-down 和/或 pinch-zoom 组合使用。*/
touch-action: pan-x;

/* 启用单指垂直平移手势。可以与 pan-x 、pan-left 、pan-right 和/或 pinch-zoom 组合使用。*/
touch-action: pan-y;

/* 启用以指定方向滚动开始的单指手势。*/
touch-action: pan-left;
touch-action: pan-right;
touch-action: pan-up;
touch-action: pan-down;

/* 启用多手指平移和缩放页面。这可以与任何平移值组合。*/
touch-action: pinch-zoom;

/* 浏览器只允许进行滚动和持续缩放操作。任何其它被 auto 值支持的行为不被支持。*/
touch-action: manipulation;