停止 touchend 无意中触发链接

3

我正在使用touchend事件来防止iOS需要两次触摸才能触发href链接,这个方法很好用,但是在滚动时会不小心触发链接。

我知道解决方法是实现touchstart以检查是否有运动,但我是jquery新手,不确定如何应用它。

以下是touchend代码

$('a').on('touchend', function(e) {
var el = $(this);
var link = el.attr('href');
window.location = link;
});

希望有人能够帮忙。

谢谢。

3个回答

5

好的,这是我为解决这个问题而使用这篇文章中的代码所运作的结果。

var dragging = false;
$("a").on("touchmove", function(){
  dragging = true;
});

$("a").on("touchend", function(e){
  if (dragging){
e.preventDefault();
}
else {var el = $(this);
var link = el.attr('href');
window.location = link;
}    

});

$("a").on("touchstart", function(){
dragging = false;
});

这对我行得通。

不错的解决方案!只需记住,jQuery并不总是简单化事情。在touchendelse语句中,您可以像这样重定向:window.location = this.href; - ToXic73

0

对我来说,这个可以工作

$('a').on('click touchend', function(e) {
    var el = $(this);
    var link = el.attr('href');
    if (link !== undefined && link !== '') {
        window.location = link;
    }
});

0

使用preventDefault

$('a').on('touchend', function(e) {
e.preventDefault();
var el = $(this);
var link = el.attr('href');
window.location = link;
});

很抱歉,那个方法不起作用。如果您在滚动时触摸到链接,它仍会意外地触发链接。您可以在这里查看:http://dev2014.rab.co.uk/ - Corey Harrison
touchstart怎么样?只需将touchend替换为touchstart即可。 - Bhojendra Rauniyar
没有 touchstart 会在点击时立即触发链接,而 touchend 会在滚动停止后触发链接。我猜需要一个 if 语句来检查是否有移动并阻止链接的触发? - Corey Harrison
你需要检测他们是否在拖动。你可以通过在 touchstart 上设置一个标志来实现这一点。感谢 @CoreyHarrison。 - ToXic73

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接