gpt4 book ai didi

jQuery(滑动与触摸)pageX 和 pageY 不断返回 0

转载 作者:行者123 更新时间:2023-12-03 21:51:39 25 4
gpt4 key购买 nike

我正在 iPhone 上玩 touchstart 和 touchend 事件。我构建了一个示例页面,其中包含 div,如果您触摸它并滚动页面,它应该返回开始位置和结束位置的 y 坐标。

链接:http://jsbin.com/ibemom/2

jQuery:

var touchStartPos;

$('.theDiv')
.bind('touchstart', function(e){
touchStartPos = e.pageY;
})
.bind('touchend', function(e){
alert(touchStartPos + ' | ' + e.pageY)
})

但是,当我在 iPhone 上加载该页面时,警报始终将这两个值报告为零。有人看出我的东西有什么问题吗?

更新:

我在 jQuery Mobile 项目中偶然发现了这段代码:https://github.com/jquery/jquery-mobile/issues/734

它的评论很突出:

 // (in iOS event.pageX and event.pageY are always 0 )

它没有说明为什么会这样,但至少我发现其他人也看到了同样的事情。将深入研究该页面上的示例代码,看看是否有解决方案。

更新二:

好吧,在查看上面链接中的示例代码后,看起来这将返回一个实际值:

e.originalEvent.touches[0].pageY

问题是,我现在意识到这并不是我所需要的。它返回我在将事件附加到的对象中触摸的区域的 Y 偏移量(与 HTML 文档相关)...而不是浏览器窗口。

我的目标是找出触摸在屏幕上的开始位置和结束位置......然后比较这些值。如果它们有很大不同,那么我们假设执行了滑动......而不是触摸。

更新三:

我还找到了这些示例的引用:

e.originalEvent.touches[0].pageX

event.targetTouches[0].pageY

虽然我似乎也无法让它们发挥作用。两者都返回未定义的错误。

更新四:

看起来一种解决方案是跟踪文档本身的 offset() 。我可以将 touchend 事件应用于文档,然后检查它的偏移量。

问题是我的 touchend 事件将首先在页面上的元素上触发,然后在文档上触发它(冒泡)。因此,在我需要弄清楚如何处理对象 touchend 事件之前,我实际上无法确定它是触摸还是滑动。

还在思考这个...

最佳答案

好吧,简单的回答是,当手指离开屏幕时,您无法检测到触摸 (touchend)。

我的第一个例子证明:http://jsfiddle.net/Y4fHD/

现在讨论解决方法。或者你想怎么调用它就怎么调用它。也许不检测 touchend 事件是有意义的,因为触摸结束。

touchmove 事件上绑定(bind)处理程序:http://jsfiddle.net/Y4fHD/1/

var endCoords = {};
$(document.body).bind("touchmove", function(event) {
endCoords = event.originalEvent.targetTouches[0];
});

然后使用变量endCoords来确定最后一次触摸

$(document.body).bind("touchend", function(event) {
$('p').text("Your end coords is: x: " + endCoords.pageX + ", y: " + endCoords.pageY);
});

好的,尝试点击您的设备!那么错误仍然会发生:为什么?因为你还没有动过你的触摸。

如果我们在 touchstart 中准备好定义 endCoords 变量,我们就在那里:http://jsfiddle.net/Y4fHD/2/

var endCoords = {};
$(document.body).bind("touchstart touchmove", function(event) {
endCoords = event.originalEvent.targetTouches[0];
});

然后使用变量endCoords来确定最后一次触摸

$(document.body).bind("touchend", function(event) {
$('p').text("Your end coords is: x: " + endCoords.pageX + ", y: " + endCoords.pageY);
});

现在尝试点击您的设备!

一些最后的注意事项是:创建变量:startCoordsendCoords,然后在touchend事件中使用它们:http://jsfiddle.net/Y4fHD/3/

var startCoords = {}, endCoords = {};
$(document.body).bind("touchstart", function(event) {
startCoords = endCoords = event.originalEvent.targetTouches[0];
});
$(document.body).bind("touchmove", function(event) {
endCoords = event.originalEvent.targetTouches[0];
});
$(document.body).bind("touchend", function(event) {
$('p').text("Your touch on the axis: " + Math.abs(startCoords.pageX-endCoords.pageX) + "x, " + Math.abs(startCoords.pageY-endCoords.pageY) + "y");
});

注意:
上面的例子都没有经过测试,希望它能起作用!
Math.abs 给出数字的绝对值,例如:-5 变成 5

关于jQuery(滑动与触摸)pageX 和 pageY 不断返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7100153/

25 4 0
文章推荐: javascript - jquery $ ('