Mobile Safari sometimes does not trigger the click event

可紊 提交于 2019-12-05 01:54:43

The click event resulting from a tap on iOS will bubble as expected under just certain conditions -- one of which you mentioned, the cursor style. Here is another:

The target element, or any of its ancestors up to but not including the <body>, has an explicit event handler set for any of the mouse events. This event handler may be an empty function.

http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html

This is much better fix vector, and can be done without a browser check. You do have to add an extra div due to the "not including the <body>" part:

<body>
  <div onclick="void(0);">
    <!-- ... all your normal body content ... -->
  </div>
</body>

Now every click event originating inside that div will bubble as expected in iOS (meaning you can catch them with $(document).on('click', '.class', etc...)).

Have you tried this?? This is because ios doesn't fire the click event sometimes, only recognizes the touch event

$(document).on('touchstart click', [Selector], [ Event ]

Just declaring these empty event listeners does the trick. Just try it :)

This will make it work on all browsers:

container.addEventListener('touchstart', () => {});
container.addEventListener('touchend', () => {});
container.addEventListener('touchcancel', () => {});
container.addEventListener('touchmove', () => {});

This is a crazy issue and indeed LinusR's answer and the description on quirksmode are accurate. My general click event listener didn't work because of this in iOS Safari:

window.addEventListener('click', function(event) {
    alert("Where's my click?!");
});

I now have wrapped my app with a <div onclick="void(0);"></div> and that works. I also added some extra things to fix some issues that came out of it:

<div onclick="void(0);" style="height: 100%; -webkit-tap-highlight-color: transparent;">
  <div style="height: 100%; -webkit-tap-highlight-color: initial;">
    <my-app></my-app>
  </div>
</div>

I needed the height: 100%; to make the click available on the whole page because I needed that. If you don't do height: 100%; the click event will still only fire within the height of the div.

The -webkit-tap-highlight-color: transparent; is to prevent an onclick flash overlay style, as iOS does this by default with clickable elements. The div after that restores the initial value of that CSS property, so that other clickable elements do have normal behavior in this regard. See this answer for more info.

xanobius

There is an additional event for mobile devices. Try to add the tap event listener in addition to the click event. They can be attached simultaneously with the following:

$(document).on('click tap', [selector], [handler])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!