javascript自定义浏览器右键菜单
HTML部分(在<body></body>之间插入以下HTML):
<div id="menu">
<ul>
<li><a href="#">contextmenuitem 1</a></li>
<li><a href="#">contextmenuitem 2</a></li>
<li><a href="#">contextmenuitem 3</a></li>
<li><a href="#">contextmenuitem 4</a></li>
<li><a href="#">contextmenuitem 5</a></li>
<li><a href="#">contextmenuitem 6</a></li>
</ul>
</div>
<div id="menu"> <ul> <li><a href="#">contextmenuitem 1</a></li> <li><a href="#">contextmenuitem 2</a></li> <li><a href="#">contextmenuitem 3</a></li> <li><a href="#">contextmenuitem 4</a></li> <li><a href="#">contextmenuitem 5</a></li> <li><a href="#">contextmenuitem 6</a></li> </ul> </div>
CSS部分:
查看代码
<style type="text/css">
*{margin:0;padding:0;}
#menu{position:absolute;width:150px;visibility:hidden;border:1px solid #666;border-bottom-width:0;}
#menu li{list-style:none;text-indent:1em;}
#menu li a{display:block;height:30px;line-height:30px;border-bottom:1px solid #666;text-decoration:none;color:#666;font:12px/30px tahoma;}
#menu li a:hover{background:#eee;color:black;}
</style>
<style type="text/css"> *{margin:0;padding:0;} #menu{position:absolute;width:150px;visibility:hidden;border:1px solid #666;border-bottom-width:0;} #menu li{list-style:none;text-indent:1em;} #menu li a{display:block;height:30px;line-height:30px;border-bottom:1px solid #666;text-decoration:none;color:#666;font:12px/30px tahoma;} #menu li a:hover{background:#eee;color:black;} </style>
JavaScript部分:
查看代码
<script type="text/javascript">
document.oncontextmenu = function(e){
if(window.event) e = window.event;
var mymenu = document.getElementById("menu");
mymenu.style.visibility = "visible";
mymenu.style.left = e.clientX + 5 +"px";
mymenu.style.top = e.clientY + 5 + "px";
return false;
}
document.onclick = function(){
var mymenu = document.getElementById("menu");
mymenu.style.visibility = "hidden";
}
</script>
<script type="text/javascript"> document.oncontextmenu = function(e){ if(window.event) e = window.event; var mymenu = document.getElementById("menu"); mymenu.style.visibility = "visible"; mymenu.style.left = e.clientX + 5 +"px"; mymenu.style.top = e.clientY + 5 + "px"; return false; } document.onclick = function(){ var mymenu = document.getElementById("menu"); mymenu.style.visibility = "hidden"; } </script>
原理:
1.利用document.oncontextmenu将浏览器的右键菜单屏蔽(return false)。
2.在CSS中将div的visibility设置为hidden,即先把它给隐藏掉,position为absolute绝对定位,这样我们就能很容易地控制left与top的值的了。
3.在函数中获取menu为mymenu,visibility为可见(visible),再设置left与top和分别等于浏览器窗口的x,y坐标,最后再写一个document.onclick函数,只要点击,就将div的可见设置为(隐藏)hidden;
我分别测试了几款浏览器,兼容性还好吧,下面是chrome效果图: