contextmenu事件:用以表示何时应该显示上下文菜单,以便开发人员取消默认的上下文菜单而提供自定义的菜单
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8"/>
<title>DOM3 event textInput</title>
<style type="text/css">
#myMenu{
position: absolute;
background: #eee;
border: 1px solid #f00;
list-style: none;
visibility: hidden;
}
</style>
</head>
<body>
<div id="myDiv">右键单击或者CTRL+单击获取自定义菜单,单击其他地方获取默认的菜单</div>
<ul id="myMenu">
<li><a href="http://www.baidu.com">百度</a></li>
<li><a href="http://www.sina.com">新浪</a></li>
<li><a href="http://www.qq.com">腾信</a></li>
</ul>
<script type="text/javascript">
window.onload = function(){
document.getElementById('myDiv').addEventListener('contextmenu',function(e){
e.preventDefault();//取消浏览器默认行为,以保证不显示浏览器默认的上下文菜单
var menu = document.getElementById('myMenu');
menu.style.left = e.clientX+"px";
menu.style.top = e.clientY+"px";
menu.style.visibility = 'visible';
},false);
document.addEventListener('click',function(){
var menu = document.getElementById('myMenu');
menu.style.left = "0px";
menu.style.top = "0px";
menu.style.visibility = 'hidden';
},false);
}
</script>
</body>
</html>
效果如下所示
自定义右键菜单的效果
网友评论