Javascript 移动设备的 X/Y 触摸坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5931172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
X/Y Touch coordinates for mobile devices
提问by Jonathon Toon
I am creating a web app that I am wanting to be usable on mobile devices. The initial mechanic of said app requires the current X/Y coordinates of the mouse - which doesn't require clicking and dragging, just simply moving the mouse around a browser window.
我正在创建一个希望在移动设备上可用的网络应用程序。该应用程序的初始机制需要鼠标的当前 X/Y 坐标 - 这不需要单击和拖动,只需在浏览器窗口中移动鼠标即可。
Now I have been looking in to the various jQuery/Javascript libraries concerning Touch and Gestures, yet I am unable to find anything that suits what I am after.
现在我一直在寻找有关 Touch 和 Gestures 的各种 jQuery/Javascript 库,但我找不到任何适合我的东西。
So basically I am looking for a way to get the x/y pos of a single finger touch/drag.
所以基本上我正在寻找一种方法来获得单指触摸/拖动的 x/y 位置。
Eg: Touch the screen at 0, 0 then hold and drag it to 480,320. The values would then interpolate between x1
, y1
to x2
, y2
.
例如:触摸屏幕 0, 0 然后按住并拖动到 480,320。然后这些值将在x1
、y1
到x2
、之间进行插值y2
。
Thanks.
谢谢。
回答by invamped
$(function() {
var $log = $("#log");
function updateLog(x, y) {
$log.html('X: '+x+'; Y: '+y);
}
document.addEventListener('touchstart', function(e) {
updateLog(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}, false);
document.addEventListener('touchmove', function(e) {
e.preventDefault();
updateLog(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
}, false);
});
回答by Tobias Cohen
You shouldn't need a library for this, it's fairly easy to write your own code using the touchstart, touchmove and touchend events.
您不应该为此需要一个库,使用 touchstart、touchmove 和 touchend 事件编写自己的代码相当容易。
http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
http://www.sitepen.com/blog/2008/07/10/touching-and-gesting-on-the-iphone/
As a side note, if you're using the iOS simulator for testing, be aware that it can sometimes give incorrect coordinates in a way that an actual device wouldn't, so you'll always need to keep a physical iOS device handy to verify that your code works.
作为旁注,如果您使用 iOS 模拟器进行测试,请注意它有时会以实际设备不会的方式提供不正确的坐标,因此您始终需要随身携带一个物理 iOS 设备验证您的代码是否有效。