我希望能够在我的Web应用程序中禁用长按(触摸和按住)图像后出现的上下文菜单。我看到了一些帖子提供了不同的想法,但是它们似乎都对我无效。是否有一种通过HTML / CSS / Javascript在Android上完成此操作的方法?
上下文菜单有其自己的事件。您只需要捕获它并停止其传播。
window.oncontextmenu = function(event) {
event.preventDefault();
event.stopPropagation();
return false;
};
如果我没记错的话,这应该可以在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>
img.addEventListener('contextmenu', function(e) { e.preventDefault(); return false; }, false);
应该可以工作,不是吗?上述解决方案将阻止所有输入。 - gman这可以通过 使用CSS 完成:
img {
pointer-events: none;
}
对于我来说,吸收所有事件并不是一个选项,因为我想禁用长按下载功能,同时仍允许用户缩放和平移图像。我能够仅通过CSS和HTML解决这个问题,方法是在图片上层叠一个“盾牌”div:
<div class="img-container">
<div class="shield"></div>
<img src="img-file.jpg">
</div>
<style>
.img-container { position: relative; }
img { max-width: 100%; }
.shield {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
}
</style>
position:relative
,以防止父容器占用所有空间。如果父容器是一个带有ontouchstart
或其他交互事件处理程序的td
,这将特别棘手,因为您不会在视觉上看到td
占用了所有区域。 - Daniel Fposition: relative
的 CSS 规则。 - Brian FitzGerald它将禁用复制功能,但不会禁止选择。
document.oncontextmenu = function() {return false;};
适用于webView。
node.ontouchstart = absorbEvent_;
node.ontouchstart = node.onclick;
-webkit-touch-callout: none;
-webkit-user-select: none; /* Disable selection/copy in UIWebView */
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;
pointer-events: none;
本质上是 CSS 中元素的 return false
,因此在这种情况下它会使我的按钮无法工作。 - Vael Victus <img {...props} onContextMenu={event => event.preventDefault()}
onTouchStart={touchStart}
onTouchEnd={touchEnd} />
<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。
您还可以捕获单击事件,并使用event.button检查哪个鼠标按钮触发了事件,在某些浏览器中是这样的。