Safari没有触发触摸事件

Pup*_*ppy 13 mobile-safari ios

我有一个小jsfiddle - http://jsfiddle.net/qhguktsn/5/.当您点击链接顶部的文本(iOS移动版Safari)时,您只会获得鼠标事件 - 根本没有触摸事件,甚至在身体上也没有.如果您点击文本底部的它,您将获得触摸事件.我们依靠触摸事件处理300ms延迟.

我们如何才能获得触摸事件以触发文本顶部和底部?

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>
Run Code Online (Sandbox Code Playgroud)

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 ")); });
Run Code Online (Sandbox Code Playgroud)

Sta*_*rov 9

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

为了解决这些问题,有几种方法.

  • 第一个是使用一个名为fastclick的小型库,它支持许多移动设备和操作系统.

  • 第二个选项是添加event.stopPropagation(); event.preventDefault();这样的.你需要他们两个.

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

还有触摸操作,但大多数移动浏览器都不支持它.:(


Dou*_*las 3

body 上的触摸事件是由于 body 元素向下移动了 margin-top,在 body 元素上放置一个轮廓来勾勒出触摸目标:

body { outline: 1px solid red; }
Run Code Online (Sandbox Code Playgroud)

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

谜团的第二部分似乎是点击目标扩展到触摸目标之外:

文字截图

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