我试图捕捉touchend
事件的触摸坐标,但未定义。 touchstart
事件运作良好,但同样的概念在touchend
失败。我用mousedown
和mouseup
构建了这个代码,that效果很好。
我错过了什么?
div.addEvent("touchstart", function (event) {
event.preventDefault(); // to avoid scrolling
span.innerHTML = event.page.x;
});
div.addEvent("touchend", function (event) {
span.innerHTML = event.page.x;
});
您需要将值存储在touchmove
上并在touchend
中读取它。
var lastMove = null;
// Save the touchstart to always have a position
div.addEvent('touchstart', function(event) {
lastMove = event;
});
// Override with touchmove, which is triggered only on move
div.addEvent('touchmove', function(event) {
lastMove = event;
});
我一直在看specification,这个4触摸事件继承自touchEvent
对象,它有3个列表属性,包含有关事件发生时所有触摸(屏幕上的每个手指)的信息,每个列表保存基于的触摸这个标准:
changedTouches
:保存目标元素表面之外的触摸。
touches
:保存所有当前触摸。
targetTouch
:保存目标元素表面内的所有当前触摸。
事件touchend保存手指在changedTouches
被抬起的位置,并且没有任何东西保存在任何其他列表中,因此如果你需要访问它,你应该使用event.changedTouches[event.changedTouches.length-1]
,这将返回一个带有pageX和pageY属性的触摸对象坐标。
整行将是:
span.innerHTML = event.changedTouches[event.changedTouches.length-1].pageX;
touchEvent
object, why you get to use them at touchstart and touchmove events, and not with touchend. Maybe the implementation added this shortcut, or I missread.
你应该在changedTouches
中使用touches
而不是touchend
div.addEvent("touchstart", function (event) {
event.preventDefault(); // to avoid scrolling
span.innerHTML = event.pageX;
});
div.addEvent("touchend", function (event) {
span.innerHTML = event.changedTouches[0].pageX;
});
虽然问题没有要求jQuery,但如果你需要一个jQuery替代品,请尝试这个代码。适用于所有最新版本的jQuery。
$(document).on('touchstart', '.className', function (e) {
console.log(e.originalEvent.touches[0].pageX);
});
$(document).on('touchend', '.className', function (e) {
console.log(e.originalEvent.changedTouches[0].pageX);
});
您可以选择省略'originalEvent',并将'changedTouches'用于仅支持JS的脚本和不支持的jQuery /浏览器。
touchStart(event) {
this.startX = event.touches[0].pageX;
},
touchEnd(event) {
this.endX = event.changedTouches[0].pageX;
},
我建议这个工作非常好,可以恢复与传统计算机相同的事件属性...
if(!('ontouchstart' in document.documentElement)){
Object.onmouseup = function(e){
your code....
}
}else{
Object.ontouchend = function(e){
e = e.changedTouches[e.changedTouches.length-1];
Your code....
}
}
非常容易管理。
*要管理您的代码,请在PC上使用Google Chrome,在控制台模式下,它会捕获TOUCH事件。