如何在iOS设备上将click替换为touchstart

10

目标

在单击时关闭锚点标签的父div。在下面的代码中,当用户单击锚点标签close_performance_tt时,我想隐藏

performance_tt

问题

在iOS设备上花费了几个小时后无法使其正常工作。在其他所有设备上都可以正常工作,甚至在BlackBerry 10设备上也可以。

<div id="performance_tt" style="display: none;width: 300px;height: 200;overflow: auto;padding: 5px;background-color: yellow;">
    <div>Website performance has become an important consideration for most sites.
    The speed of a website affects usage and user satisfaction, as well as search engine rankings, a factor that directly correlates to revenue and retention.
    As a result, creating a system that is optimized for fast responses and low latency is key.</div>
    <a id="close_performance_tt" href="#">Close</a>
    <script>
    var userAgent = navigator.userAgent.toLowerCase();
    var isiOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
    if (isiOS) {
        $("#close_performance_tt").bind('touchstart', function() {
            alert('Touch-start event triggered');
        });
    } else {
        $("#close_performance_tt").bind('click', function() {
            alert('Click event triggered');
        });
    }
    </script>
</div>

为什么不使用 $("#close_performance_tt").bind('click touchstart', ..) 而不是 if..else - Arun P Johny
但这不是问题的原因,对吧? - KalC
1
你必须确保标志 isiOS 具有正确的值。 - Arun P Johny
3个回答

18
定义一个点击事件处理程序,以便稍后使用:
var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");

$("a").bind(clickHandler, function(e) {
    alert("clicked or tapped. This button used: " + clickHandler);
});

这将在非触摸设备上触发点击事件,在触摸设备上触发touchstart事件。

话虽如此,我强烈推荐使用Fast click,并使用常规的点击事件。使用上述解决方案时,例如在滑动链接以滚动页面时,将触发链接的 "touchstart" - 这并不理想。


3
请见http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html 对于iOS上的鼠标事件(如点击),除非以下情况之一,否则不会冒泡:
  • 事件的目标元素是链接或表单字段。
  • 目标元素或其祖先中有明确为任何鼠标事件设置的事件处理程序。此事件处理程序可以是一个空函数。
  • 目标元素或其祖先中包括文档,具有cursor: pointer CSS声明。
  • 最简单的解决方法是在iOS触摸设备上到处应用cursor: pointer。由于没有光标,因此它没有任何视觉影响。

    非常有用的答案,大家请注意!谢谢,Sebastian。 - mcmxc

    2

    如果我使用你的代码,在弹出警告之前我需要点击两次。随后,我需要点击大约4次才能显示警告。但是使用以下代码,警告总是触发。$("#close_performance_tt").bind('click touchstart',function() { alert('事件已注册。'); }); - KalC
    1
    我刚在我的iPad上测试了代码,它运行良好。确保您只点击一次,如果按住或双击则不会触发“点击”事件。 - BMH
    1
    我没有iPad。在iPhone 4S上测试了一下,但是没有成功。几个小时后我会在iPad上测试,并且再次回复您。 - KalC

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