我想禁用在我的网络应用程序中对图像进行长按(触摸并按住)后出现的上下文菜单。我看过不同想法的帖子怎么做,但它们似乎都不适合我。
有没有办法通过HTML / CSS / Javascript在Android上执行此操作?
答案 0 :(得分:133)
上下文菜单有自己的事件。你只需要抓住它并阻止它传播。
window.oncontextmenu = function(event) {
event.preventDefault();
event.stopPropagation();
return false;
};
答案 1 :(得分:32)
这应该适用于1.6或更高版本(如果我没记错的话)。我不相信1.5或更早的解决方法。
<!DOCTYPE html>
<html>
<head>
<script>
function absorbEvent_(event) {
var e = event || window.event;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
function preventLongPressMenu(node) {
node.ontouchstart = absorbEvent_;
node.ontouchmove = absorbEvent_;
node.ontouchend = absorbEvent_;
node.ontouchcancel = absorbEvent_;
}
function init() {
preventLongPressMenu(document.getElementById('theimage'));
}
</script>
</head>
<body onload="init()">
<img id="theimage" src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>
答案 2 :(得分:8)
对我来说,吸收所有事件不是一个选择,因为我想禁用长按下载,同时仍允许用户缩放和平移图像。我只能通过在图像顶部分层“屏蔽”div来解决这个问题,如下所示:
<div class="img-container">
<div class="shield"></div>
<img src="path.jpg">
</div>
img {
max-width: 100%;
}
.shield {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
}
希望这有助于某人!
答案 3 :(得分:5)
我使用Nurik的完整示例,但元素(我页面中的输入图像)也被禁用了点击。
我改变原来的行:
原帖:
node.ontouchstart = absorbEvent_;
我的改变:
node.ontouchstart = node.onclick;
使用此approuch我在logpress上禁用弹出式保存图像菜单,但保持点击事件。
我在Dolphin HD浏览器下使用Android 2.2进行7英寸平板电脑测试,效果很好!
答案 4 :(得分:5)
可以做using CSS:
img {
pointer-events: none;
}
答案 5 :(得分:3)
将此CSS代码用于移动设备
-webkit-touch-callout: none;
-webkit-user-select: none; /* Disable selection/copy in UIWebView */
答案 6 :(得分:0)
<a id="moo" href=''> </a>
<script type="text/javascript">
var moo = document.getElementById('moo');
function handler(event) {
event = event || context_menu.event;
if (event.stopPropagation)
event.stopPropagation();
event.cancelBubble = true;
return false;
}
moo.innerHTML = 'right-click here';
moo.onclick = handler;
moo.onmousedown = handler;
moo.onmouseup = handler;
</script>
捕获onContextMenu事件,并在事件处理程序中返回false。
您还可以捕获click事件,并在某些浏览器中检查使用event.button触发事件的鼠标按钮。
答案 7 :(得分:0)
刚遇到类似的问题。以上建议在Andoid浏览器中对我不起作用,但我发现将有问题的图像显示为CSS背景图像而不是嵌入图像可以解决问题。
答案 8 :(得分:0)
pointer-events: none; // for Android
-webkit-touch-callout: none; // for iOS
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
答案 9 :(得分:0)
我遇到了类似的问题。我在同一问题(Preventing default context menu on longpress / longclick in mobile Safari (iPad / iPhone))上尝试了该线程和另一个野生动物园线程的解决方案。糟糕的是我无法使用onTouchStart,onTouchEnd等...
仅阻止onContextMenu中的事件。 React 16.5.2的片段。 仅在镀铬中测试。
<img {...props} onContextMenu={event => event.preventDefault()}
onTouchStart={touchStart}
onTouchEnd={touchEnd} />
希望它对某人有帮助。干杯!
答案 10 :(得分:0)
它将禁用复制,但不会禁用选择。
document.oncontextmenu = function() {return false;};
在webView中工作。
答案 11 :(得分:-3)
通过原始javascript,没有为上下文菜单调用的事件。也许在Java世界中有一些东西......在Android webkit中实际上有几个关于javascript事件的问题(例如焦点无法正常工作)。