gpt4 book ai didi

javascript - 在 touchend 事件中检索 touchstart 坐标

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:21 25 4
gpt4 key购买 nike

当发生 touchend 事件时,是否可以知道触摸从哪里开始(touchstart 坐标)?乍一看,这看起来就像在 touchstart 期间保存坐标一样简单,但假设该事件附加到具有特定类(即 .special)的所有 DOM 元素。现在考虑我用 .special 类触摸两个对象,然后将手指从一个对象上移开。我不能只看最后保存的值,因为它可能是我抬起的第一根手指。

在这些情况下如何检索触摸开始坐标?

最佳答案

touchstart 上,您可以存储您可能需要的所有值(如 x、y、目标等)。在 touchend 上,您可以检索所有存储的值,这要归功于 Touch.identifier 值,该值对于每次触摸都应该是唯一的。

我在这里创建了一个概念证明: http://jsbin.com/adifit/3/

下面的代码仅跟踪 xy 位置,但如果需要,您可以跟踪任何属性。

代码背后的想法是:

  1. touchstart上创建一个对象并将所有数据存储在里面(包括touch ID)
  2. 将这个对象存入数组
  3. touchend上检查触摸的id并尝试在数组中找到相应的对象
  4. 如果找到,我们就完成了。

还有代码:

var touches = [];
var cons;

$(init);

function init()
{
cons = $("#console");
document.getElementById("area").addEventListener("touchstart", onTouchStart);
document.addEventListener("touchend", onTouchEnd);
document.addEventListener("touchcancel", onTouchEnd);
}

function onTouchStart(e)
{
e.preventDefault();
var touchList = e.changedTouches;
var touch;
for(var i = 0; i < touchList.length; i++)
{
cons.html(cons.html() + "startX: " + touchList[i].screenX + ", id: " + touchList[i].identifier + "<br/>");
touch = {x: touchList[i].screenX, y: touchList[i].screenY, id: touchList[i].identifier};
touches.push(touch);
}
}

function onTouchEnd(e)
{
cons.html(cons.html() + "<strong>TouchEnd:</strong><br/>");
var touchList = e.changedTouches;
var touch;
for(var i = 0; i < touchList.length; i++)
{
touch = {x: touchList[i].screenX, y: touchList[i].screenY, id: touchList[i].identifier};
for (var j = touches.length - 1; j >= 0 ; j--)
{
if (touches[j].id == touch.id)
{
cons.html(cons.html() + "<strong>startX: "+ touches[j].x+ ", id: " + touchList[i].identifier + "</strong><br/>");
touches.splice(j, 1);
}
}
}
}

上面的代码使用了 jQuery,但它只是为了方便在屏幕上显示结果而使用,jQuery 没有用于其他任何用途。

关于javascript - 在 touchend 事件中检索 touchstart 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com