not working in Safari/iOS?

2020-07-18 10:18发布

I have this code in my page:

<a href onClick="return false;">Press me!</a>

The link is placed inside a span with a useful onClick event.

Now, in Chrome and Firefox this works perfectly. The link is clicked, the useful event is executed and everybody's happy. In iOS (iPhone and iPad) using the default Safari browser, this fails miserably - after the link is clicked the whole page is reloaded and the useful event is never executed.

I also tried

<a href="#" onClick="return false;">Press me!</a>

Which I understood to be the wrong way of doing this. In Chrome and Firefox it works well, but in iOS' Safari it jumped back to the beginning of the page (but it DID execute the useful event, so in a sense it was better).

What am I missing?

标签: html ios
3条回答
三岁会撩人
2楼-- · 2020-07-18 10:37

From your description, it seems like a bug in iOS browser JS implementation (maybe create a minimal code to demonstrate it?).

A simple workaround would be to replace the <a href...> with <span style="cursor:pointer;">.

查看更多
你好瞎i
3楼-- · 2020-07-18 10:51

You can set href="#", and I'm noticing the same jumping to the top of the page. # is an in-page anchor, which I believe refers to the top of the page. I'm not clear on the defined behavior for that. But alas, you want to cancel it.

In the iPhone 5.0.1 Simulator, combining both cancelation methods works and doesn't scroll to the top. This is my complete test.html file. It works in the simulator, Chrome and OS X Safari.

<div style="height: 1000px; background-color: blue;"></div>
<a href="#" onClick="event.preventDefault(); return false;">Poke it!</a>
<div style="height: 1000px; background-color: red;"></div>

For the record, removing the event.preventDefault(); duplicates your bug.

查看更多
乱世女痞
4楼-- · 2020-07-18 10:53

Have you tried binding the element purely from javascript?

<a href="#" id="nogo">Foo</a>

document.getElementById('nogo').onclick = function(ev) {
ev.preventDefault();
};
查看更多
登录 后发表回答