Safari 不触发触摸事件

Safari not firing touch events

我有一个小的 jsfiddle - http://jsfiddle.net/qhguktsn/5/。当您点击 link(iOS 移动版 Safari)顶部的文本时,您只会收到鼠标事件 - 根本没有触摸事件,甚至在 body 上也没有。如果你在文本底部点击它,你会得到触摸事件。我们依靠触摸事件来处理 300 毫秒的延迟。

我们如何获取点击文本顶部和底部的触摸事件?

HTML:

<div style="margin-left:200px;margin-top:200px">
    <a style="vertical-align:center;height: 20px, width: 20px;font-size:100px" href="javascript: void 0">text</a>
</div>

JS:

jQuery("a").on("mousedown", function() { document.body.appendChild(document.createTextNode("mousedown ")); });
jQuery("a").on("mouseup", function() { document.body.appendChild(document.createTextNode("mouseup ")); });
jQuery("a").on("touchstart", function() { document.body.appendChild(document.createTextNode("touchstart ")); });
jQuery("a").on("touchend", function() { document.body.appendChild(document.createTextNode("touchend ")); });
jQuery("a").on("click", function() { document.body.appendChild(document.createTextNode("click ")); });

jQuery(document.body).on("touchstart", function() { document.body.appendChild(document.createTextNode("body touchstart ")); });
jQuery(document.body).on("touchend", function() { document.body.appendChild(document.createTextNode("body touchend ")); });

body 上的触摸事件是由于 body 元素被 margin-top 向下移动,在 body 元素上放置轮廓 [= =25=]:

body { outline: 1px solid red; }

http://jsfiddle.net/qhguktsn/11/

神秘的第二部分似乎是点击目标扩展到touch-target之外:

触摸红色轮廓不会触发 body 元素上的触摸事件,但在扩展到锚点本身之外的灰色 -webkit-tap-highlight-color 区域内的任何地方点击时似乎会触发点击事件。因此,点击最顶部将触发锚点上的点击事件,但不会触发 body.

上的触摸事件

这是 Mobile Safari 中的已知错误。 https://bugs.webkit.org/show_bug.cgi?id=105406 还有另一个从不同的文档添加节点。 https://bugs.webkit.org/show_bug.cgi?id=135628

为了修复它们,有几种方法。

  • 第一个是使用一个叫做fastclick的小库,它支持很多移动设备和OS。

  • 第二个选项是这样添加event.stopPropagation(); event.preventDefault();。两者你都需要。

    jQuery("a").on("mousedown", function(event) {
        event.stopPropagation();
        event.preventDefault();
        document.body.appendChild(document.createTextNode("mousedown ")); 
    });
    
  • 第三个选项是使用像 <meta name="viewport" content="width=device-width, user-scalable=no"> 这样的视口元标记。这将消除所有触摸延迟,没有任何解决方法。但是,再次在 Safari 上,它可能不像在其他浏览器中那样运行,因为嘿 Safari is the new IE

还有touch-action,但大多数移动浏览器不支持它。 :(

我发现当点击 position:fixed 元素包含的超出 window 的元素时,不会触发触摸事件。我通过缩短父容器来处理这个问题(使用 JS 来获得准确的 window 高度)。

此问题出在使用 iOS10 的应用程序 UIWebview 中。(是的,仍在使用 UIWebview)