首页 > 解决方案 > 如何在 Javascript/jQuery 中获取触摸坐标?

问题描述

这是我正在使用的代码

$(document).on("mousemove touchmove",function(e){
    var currentY = e.originalEvent.touches ?  e.originalEvent.touches[0].clientY : e.clientY;
    var currentX = e.originalEvent.touches ?  e.originalEvent.touches[0].clientX : e.clientX;
    //do stuff with the coordinates
});

它工作得很好,但是在移动设备上存在一些滞后(在 Android 上测试)。

延迟的原因是位于移动浏览器顶部的导航栏(例如 Android 上的 Chrome)。

如果用户向下滚动,导航栏就会消失,并且触摸事件会完美运行。

下面的代码禁用页面滚动,并且触摸事件完美运行。但是,我不想阻止用户滚动(因为它是必需的)

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

存在导航栏时如何防止延迟?

标签: javascriptjquery

解决方案


听起来触摸事件被地址栏隐藏的动作所捕获,我认为没有办法阻止这种情况,除了强制导航栏始终保持可见。您可以使用 Submachine23 在此答案中的 css 完成此操作,我将在此处复制以供后代使用。

html {
  background-color: red;
  overflow: hidden;
  width: 100%;
}

body {
  height: 100%;
  position: fixed;
  /* prevent overscroll bounce*/
  background-color: lightgreen;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  /* iOS velocity scrolling */
  width: 50%;
  margin-left: 25%;
}

推荐阅读