如何在iOS设备上用touchstart替换click

Kal*_*alC 8 jquery click ipad touchstart

目的

单击时关闭锚标记的父div.在下面的代码中,我想在用户单击锚标记close_performance_tt时隐藏div 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>
Run Code Online (Sandbox Code Playgroud)

cur*_*ets 16

定义一个稍后可以使用的clickhandler:

var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");

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

这将触发点击非触摸设备和触摸设备上的触摸启动.

说到这一点,我强烈建议使用快速点击,并使用常规点击事件.使用上述解决方案,当您在其上滑动以滚动页面时,您将在链接上触发"touchstart" - 这是不理想的.

  • 当用户有带鼠标插入的触摸设备时,这是一个坏主意... (2认同)