我正在使我的网站触摸友好,并创建了一个简单的轮播风格插件,效果很好,但是当触发 touchend 事件并且原始目标是图像时(用户触摸图像,然后滑动/向左进行导航)它仍在打开与图像关联的链接。
我已经添加了 event.stopPropagation() 和 event.preventDefault() 但没有效果。
有人知道如何防止这种情况吗?
编辑:
我使用以下方式绑定(bind)触摸事件:
obj.parent().bind('touchstart', onTouchStart);
obj.parent().bind('touchend', onTouchEnd);
这是 touchend 函数
function onTouchEnd(event) {
if(!cdata.in_touch) return;
cdata.in_touch = false;
var pos = getPointerPosition(event);
var final_distance = Math.sqrt(pos.x - cdata.touch_start);
cdata.timer_end = new Date();
cdata.timer_length = cdata.timer_end - cdata.timer_start;
if(cdata.timer_length > 100) {
if (final_distance > 100) {
event.stopPropagation();
event.preventDefault();
// no effect, link associated with image still fires
return;
}
}
}
最佳答案
解决这个问题的一般技术是监听touchstart
。触发 touchstart
后,保存触摸 X-Y 坐标并附加 touchend
和 touchmove
的监听器。 touchend
监听器应该调用您想要调用的指定回调(即全屏显示点击的图像)。 touchmove
应该监控从原始点击 X-Y 坐标移动的距离,如果超过某个阈值,它就会取消 touchend
(以及现在多余的 touchmove
事件)。
Google 有一篇很棒的文章提供了执行此操作的引用代码 https://developers.google.com/mobile/articles/fast_buttons
此外,FTlabs 推出了一个名为 FastClick 的新 Github 项目,该项目更加全面; https://github.com/ftlabs/fastclick
关于touch - jquery - 如果原始目标是链接/图像,则 touchend PreventDefault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13820695/