如何防止本机浏览器默认捏缩放行为? [英] How to prevent native browser default pinch to zoom behavior?

查看:35
本文介绍了如何防止本机浏览器默认捏缩放行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题被问到了几种不同的风格,但没有一个令人满意.

This question has been asked in a couple different flavors, but none satisfy.

本机浏览器(例如 Mac 版 Google Chrome)默认支持捏合缩放"手势,这将缩放整个视口.如何禁用(响应)此默认行为,以便我可以编写自己的缩放/缩放逻辑?Google 地图 https://maps.google.com/ 似乎已经实现了这一点,因为在地图上捏合仅缩放地图区域,其余 UI 保持不变,同时捏合左侧边栏显示默认行为.

The native browser (Google Chrome for Mac, for instance) supports the "pinch to zoom" gesture by default which will zoom the whole viewport. How do I disable (react to) this default behavior so I can write my own pinching/zooming logic? Google Maps https://maps.google.com/ seems to have achieved this since pinching on the map will only scale the map area, leaving the rest of the UI intact, while pinching on the left sidebar shows the default behavior.

我尝试了一些方法,例如 HTML "viewport" 元标记、CSS touch-action: none; 和 JavaScript document.addEventListener('touchmove', e => { e.preventDefault() }),但它们似乎都只适用于移动设备.

I have tried a few approaches such as HTML "viewport" meta tag, CSS touch-action: none; and JavaScript document.addEventListener('touchmove', e => { e.preventDefault() }), but they all seem to only work on mobile.

推荐答案

我偶然发现了一个适用于 Chrome 的解决方案.您基本上必须preventDefault wheel" 事件.ctrlKey 将是 true 如果它是捏合事件而不是滚动.

I accidentally found a solution which works on Chrome. You basically have to preventDefault the "wheel" event. ctrlKey will be true if it is a pinch event instead of a scroll.

element.addEventListener('wheel', event => {
   const { ctrlKey } = event
   if (ctrlKey) {
      event.preventDefault();
      return
   }
}, { passive: false })

我猜这就是 Google 地图的做法.

I'd guess this is how Google Maps does it.

(大多数)跨浏览器解决方案可能是上述技术的组合:user-scalable=no 在浏览器的 viewport" 元标记中确实支持它,而这个支持原生 Chrome.

The (most) cross-browser solution is probably a combination of the techniques mentioned: user-scalable=no in the "viewport" meta tag for the browsers that do support it and this one for native Chrome.

这篇关于如何防止本机浏览器默认捏缩放行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆