2011-05-04 52 views
10

我试图从触摸事件(例如touchstart)获取触摸坐标相对于浏览器的视口。我试图从clientX/Y属性中获取它们,但实际上它们都返回包括滚动的值。包括触摸事件clientX/Y是否滚动?

这是违反规范,因为它说客户端X/Y应该返回坐标而不滚动。

  • 我试着添加/删除元视口标签 - 没有成功。
  • 我在iPhone和Fennec上每天在iOS 4.3上进行测试,两者都通过滚动返回值。

我在做什么错了?

感谢

回答

7

试试这个

event.touches[0].pageX 

注意,它总是event.touches即使您定义的事件是这样的(使用jquery这里)

$("body").bind('touchmove', function(e){ 
//stops normal scrolling with touch 
e.preventDefault(); 

console.log(event.touches[0].pageX) 

}) 

;

Safari guide提供更详细

+0

是的,我通过event.touches [0] .clientX检索它...但我仍然不知道为什么(iOS至少)报告pageX和clientX相同(实际上它们应该因视口偏移而有所不同) – kuvik 2011-05-04 17:37:30

+1

你是对的,看起来像一个错误。您可以通过抵消页面滚动来解决这个问题'(event.targetTouches [0] .screenY - $(window).scrollTop())' – 2011-05-04 21:25:39

+0

e.originalEvent.touches [0] .clientY正在为我工​​作 – 2015-06-06 14:38:45

14

你没有做错什么。这是在页面滚动时发生的旧版webkit中的一个错误。我已经看到了iOS4中的这个错误,以及Android 4.0中的一个不同的错误。

我发现了一种检测错误并计算正确值的方法。希望这对其他人有用:

function fixTouch (touch) { 
    var winPageX = window.pageXOffset, 
     winPageY = window.pageYOffset, 
     x = touch.clientX, 
     y = touch.clientY; 

    if (touch.pageY === 0 && Math.floor(y) > Math.floor(touch.pageY) || 
     touch.pageX === 0 && Math.floor(x) > Math.floor(touch.pageX)) { 
     // iOS4 clientX/clientY have the value that should have been 
     // in pageX/pageY. While pageX/page/ have the value 0 
     x = x - winPageX; 
     y = y - winPageY; 
    } else if (y < (touch.pageY - winPageY) || x < (touch.pageX - winPageX)) { 
     // Some Android browsers have totally bogus values for clientX/Y 
     // when scrolling/zooming a page. Detectable since clientX/clientY 
     // should never be smaller than pageX/pageY minus page scroll 
     x = touch.pageX - winPageX; 
     y = touch.pageY - winPageY; 
    } 

    return { 
     clientX: x, 
     clientY: y 
    }; 
} 

必须为event.touches数组中的每个触摸调用此函数。