是否包含Touch Events clientX / Y滚动? [英] Includes Touch Events clientX/Y scrolling or not?
问题描述
我正在尝试从触摸事件(例如 touchstart )获取相对于浏览器的视口的触摸坐标。我试图从clientX / Y属性中获取它们,但两者实际上都返回值包括滚动。
I'm trying to get touch coordinates relative to the viewport of browser from touch events (such as touchstart). I tried to get them from clientX/Y properties, but both actually return values including scrolling.
这是违反规范的,因为它说clientX / Y应该返回坐标而不滚动。
This is against spec, as it says clientX/Y should return coordinates without scrolling.
- 我尝试添加/删除元视口标记 - 但没有成功。
- 我测试了它iPhone上的iOS 4.3和每晚的Fennec - 都滚动返回值。
我做错了什么?
谢谢
推荐答案
你没有做错任何事。这是滚动页面时旧版webkit中的错误。我在iOS4中看到了这个错误,在Android 4.0中看到了一个不同的错误。
You're not doing anything wrong. It's a bug in older versions of webkit that occur when the page is scrolled. I have seen this bug in iOS4 and a different bug in Android 4.0.
我找到了一种检测错误并计算正确值的方法。希望这对其他人有用:
I've found a way to detect the bugs and calculate the correct values. Hope this can be useful for others:
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数组中为每次触摸调用此函数。
This function has to be called for each touch in the event.touches array.
这篇关于是否包含Touch Events clientX / Y滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!