本文解決的問題:1、實現右鍵菜單功能代碼;2、阻止默認事件的實際應用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>右鍵菜單</title>
<style type="text/css">
#menu {
position: fixed;
left:0;
top:0;
width:200px;
height: 400px;
background-color: blue;
display: none;
}
</style>
</head>
<body>
<div id="menu">
</div>
<script type="text/javascript">
var menu = document.getElementById("menu");
document.oncontextmenu = function(e) {
var e = e || window.event;
//鼠標點的坐標
var oX = e.clientX;
var oY = e.clientY;
//菜單出現後的位置
menu.style.display = "block";
menu.style.left = oX + "px";
menu.style.top = oY + "px";
//阻止浏覽器默認事件
return false;//一般點擊右鍵會出現浏覽器默認的右鍵菜單,寫了這句代碼就可以阻止該默認事件。
}
document.onclick = function(e) {
var e = e || window.event;
menu.style.display = "none"
}
menu.onclick = function(e) {
var e = e || window.event;
e.cancelBubble = true;
}
// document.addEventListener("contextmenu",function(e){
// var e = e || window.event;
// e.preventDefault();
// alert("menu");
// },false)
</script>
</body>
</html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。