IOS HTML 禁用双击缩放

新手上路,请多包涵

我正在设计一个主要专注于数据输入的网站。在我的一个表单中,我有一些按钮可以快速增加和减少表单字段中的数字值。我在用

<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

禁用似乎使用 IOS 的 Firefox 应用程序工作的缩放。然而,当另一位用户使用 Safari 对其进行测试时,点击按钮的速度过快导致页面放大,分散了用户的注意力,无法快速增加数值。似乎从 IOS 10 开始,苹果出于可访问性原因删除了 user-scalable=no ,这就是为什么它只适用于 Firefox 等第三方浏览器的原因。我发现最接近禁用双击缩放的是这个

var lastTouchEnd = 0;
document.addEventListener('touchend', function (event) {
    var now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        event.preventDefault();
    }
    lastTouchEnd = now;
}, false);

来自 https://stackoverflow.com/a/38573198 但是,这会完全禁用快速点击,这虽然会阻止双击缩放,但也会阻止用户快速输入值。有什么方法可以让快速按下按钮,同时禁用双击缩放吗?

原文由 tchatow 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 874
2 个回答

我做了一个有点复杂的答案,但它在停止双击和双指缩放方面工作得非常好和可靠,并且允许几乎所有其他类型的交互

let drags = new Set() //set of all active drags
document.addEventListener("touchmove", function(event){
  if(!event.isTrusted)return //don't react to fake touches
  Array.from(event.changedTouches).forEach(function(touch){
    drags.add(touch.identifier) //mark this touch as a drag
  })
})
document.addEventListener("touchend", function(event){
  if(!event.isTrusted)return
  let isDrag = false
  Array.from(event.changedTouches).forEach(function(touch){
    if(drags.has(touch.identifier)){
      isDrag = true
    }
    drags.delete(touch.identifier) //touch ended, so delete it
  })
  if(!isDrag && document.activeElement == document.body){
    //note that double-tap only happens when the body is active
    event.preventDefault() //don't zoom
    event.stopPropagation() //don't relay event
    event.target.focus() //in case it's an input element
    event.target.click() //in case it has a click handler
    event.target.dispatchEvent(new TouchEvent("touchend",event))
    //dispatch a copy of this event (for other touch handlers)
  }
})

注意:格雷格的回答并不一致(双击某些元素仍会缩放)

如果你想防止双指缩放,你需要一些 JS CSS(不要问我为什么):

 document.addEventListener('touchmove', function(event){
  if (event.scale !== 1) event.preventDefault(); //if a scale gesture, don't
})

*{touch-action: pan-x pan-y} /*only allow scroll gestures*/

原文由 BlobKat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题