【问题标题】:Stop touchend firing links unintentionally无意中停止 touchend 触发链接
【发布时间】:2014-04-22 12:18:59
【问题描述】:

我正在使用touchendevent 来防止ios 需要两次触摸才能触发href 链接。 这工作正常,但它会在滚动时无意中触发链接。

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

这是touchendcode

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

希望有人能提供帮助。

谢谢

【问题讨论】:

    标签: jquery ios touch-event


    【解决方案1】:

    使用preventDefault:

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

    【讨论】:

    • 恐怕这行不通。如果您在滚动时触摸链接,它仍然会无意中触发链接。你可以在这里看到:dev2014.rab.co.uk
    • touchstart 怎么样?只需将 touchend 替换为 touchstart。
    • 没有 touchstart 在单击时立即触发链接,而 touchend 在滚动停止后触发链接。我猜需要有一个 if 语句来检查是否有移动并阻止链接触发?
    • 您需要检测它们是否在拖动。你可以通过在touchstart 上设置一个标志来做到这一点。感谢@CoreyHarrison
    【解决方案2】:

    好的,这就是我使用this post 中的代码解决这个问题的方法

    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 并不总是简单的事情。在touchend 上的else 语句中,您可以像这样进行重定向:window.location = this.href;
    【解决方案3】:

    对我来说这个很有效

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多