问题
This question already has an answer here:
- How do I disable right click on my web page? 23 answers
Not that I\'m trying to prevent \'View Source\' or anything silly like that, but I\'m making some custom context menus for certain elements.
EDIT: response to answers: I\'ve tried this:
<a id=\"moo\" href=\'\'> </a>
<script type=\"text/javascript\">
var moo = document.getElementById(\'moo\');
function handler(event) {
event = event || window.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>
回答1:
Capture the onContextMenu event, and return false in the event handler.
You can also capture the click event and check which mouse button fired the event with event.button, in some browsers anyway.
回答2:
If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag
<body oncontextmenu="return false;">
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well)
However, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.
回答3:
I have used this:
document.onkeydown = keyboardDown;
document.onkeyup = keyboardUp;
document.oncontextmenu = function(e){
var evt = new Object({keyCode:93});
stopEvent(e);
keyboardUp(evt);
}
function stopEvent(event){
if(event.preventDefault != undefined)
event.preventDefault();
if(event.stopPropagation != undefined)
event.stopPropagation();
}
function keyboardDown(e){
...
}
function keyboardUp(e){
...
}
Then I catch e.keyCode property in those two last functions - if e.keyCode == 93, I know that the user either released the right mouse button or pressed/released the Context Menu key.
Hope it helps.
回答4:
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
回答5:
You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.
来源:https://stackoverflow.com/questions/381795/how-to-disable-right-click-context-menu-in-javascript