在移动Safari(iPad / iPhone)中防止longpress / longclick上的默认上下文菜单 [英] Preventing default context menu on longpress / longclick in mobile Safari (iPad / iPhone)
问题描述
对于网站,我想在用户长按屏幕时显示自定义上下文菜单。我在我的代码中创建了一个 jQuery Longclick 监听器,以显示自定义上下文菜单。将显示上下文菜单,但也会显示iPad的默认上下文菜单!我尝试通过添加 preventDefault()
我的监听器中的事件,但这不起作用:
For a website I want to show a custom context menu when a user "longpresses" the screen. I've created a jQuery Longclick listener in my code to show a custom context menu. The context menu is displayed, but the iPad's default context menu is also displayed! I tried to prevent this by adding a preventDefault()
to the event in my listener, but this does not work:
function showContextMenu(e){
e.preventDefault();
// code to show custom context menu
}
$("#myId").click(500, showContextMenu);
问题
- 你可以阻止显示iPad的默认上下文菜单吗?
- 可以使用jQuery Longclick插件完成吗?
Longclick插件具有针对iPad的一些特定处理(假设通过此片段它的源代码):
if (!(/iphone|ipad|ipod/i).test(navigator.userAgent)){
$(this)
.bind(_mousedown_, schedule)
.bind([_mousemove_, _mouseup_, _mouseout_, _contextmenu_].join(' '), annul)
.bind(_click_, click)
}
所以我认为这回答了我的第二个问题(假设插件使用了正确的事件)。
So I assume this answers my second question (assuming the plugin used the correct event).
推荐答案
感谢指向的JDandChips我的解决方案。它与longclick插件结合使用非常完美。为了文档起见,我会发布自己的答案来展示我的所作所为。
Thanks to JDandChips for pointing me to the solution. It works perfectly in combination with the longclick plugin. For documentation sake I'll post my own answer to show what I did.
HTML:
<script type="text/javascript"
src="https://raw.github.com/pisi/Longclick/master/jquery.longclick-min.js"></script>
<p><a href="http://www.google.com/">Longclick me!</a></p>
Javascript已经可以了:
The Javascript already was OK:
function longClickHandler(e){
e.preventDefault();
$("body").append("<p>You longclicked. Nice!</p>");
}
$("p a").longclick(250, longClickHandler);
修复方法是将这些规则添加到样式表中:
The fix was to add these rules to the style sheet:
body { -webkit-touch-callout: none !important; }
a { -webkit-user-select: none !important; }
更新: jQuery Longclick 插件似乎仅适用于iPad上的Safari,而不适用于Google Chrome !我正在调查此事。
Update: the jQuery Longclick plugin seems to work only in Safari on the iPad, not in Google Chrome! I'm looking into that at the moment.
更新2 :我已嵌入因为我在Chrome中遇到以下错误(由于 https
),因此在小提琴源中出现了Longclick Javascript:
Update 2: I've embedded the Longclick Javascript in the source of the Fiddle because I was getting the following error in Chrome (due to https
):
拒绝从'执行脚本https://raw.github.com/pisi/Longclick/master/jquery.longclick-min.js '因为其MIME类型('text / plain')不可执行,并且启用了严格的MIME类型检查。
Refused to execute script from 'https://raw.github.com/pisi/Longclick/master/jquery.longclick-min.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
查看更新版本: http://jsfiddle.net/z9ZNU/53/
这篇关于在移动Safari(iPad / iPhone)中防止longpress / longclick上的默认上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!