Example
Execute JavaScript when the user right-clicks the mouse on the
<div oncontextmenu="myFunction()" contextmenu="mymenu">
Define and use the
oncontextmenu event Fires and opens the context menu when the user right-clicks the mouse on an element.
Note: All browsers support the oncontextmenu event, and the contextmenu element is only supported by the Firefox browser.
Browser support
Syntax
HTML:
<element oncontextmenu="myScript">
JavaScript:
object.oncontextmenu=function(){myScript};
##In JavaScript, use the addEventListener() method:
object.addEventListener("contextmenu", myScript);
Technical details
Yes | |
Yes | |
MouseEvent | |
All HTML elements |
<!doctype html> <html> <head> <!--声明当前页面编码集(中文编码<gbk,gb2312>,国际编码<utf-8>)--> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="keywords" content="关键词,关键词"> <meta name="description" content=""> <title> html </title> <style type="text/css"> *{padding:0px;margin:0px;} body{height:2000px;} </style> </head> <body> <script> /*屏蔽鼠标右键的默认事件*/ document.oncontextmenu = function(){ return false; }; /*屏蔽按空格键是滚动条向下滚动*/ document.onkeydown = function(ev){ var e = ev||event; if(e.keyCode == 32){ return false; } } </script> </body> </html>
<!doctype html>
<html>
<head>
<!--声明当前页面编码集(中文编码<gbk,gb2312>,国际编码<utf-8>)-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="keywords" content="关键词,关键词">
<meta name="description" content="">
<title> html </title>
<style type="text/css">
*{padding:0px;margin:0px;}
#box{display:none;width:150px;height:200px;background:gray;position:fixed;}
</style>
</head>
<body>
<div id="box"></div>
<script>
var obox = document.getElementById("box");
/*点击鼠标右键时执行*/
document.oncontextmenu = function(ev){
var e = ev||window.event;
var x = e.clientX;
var y = e.clientY;
obox.style.cssText = "display:block;top:"+y+"px;left:"+x+"px;";
return false;
};
/*点击空白处隐藏*/
document.onclick = function(){
obox.style.display = "none";
};
</script>
</body>
</html>
The above is the detailed content of oncontextmenu event in html that runs a script when the context menu is triggered. For more information, please follow other related articles on the PHP Chinese website!