代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
ul, ul li{
list-style:none;
}
#list{
width:80px;
border:1px solid #ccc;
box-shadow:2px 2px 2px #ccc;
display:none;
position: absolute;
}
#list li{
border-bottom:1px solid #ccc;
height:24px;
line-height:24px;
text-align:center;
cursor: pointer;
}
#list li:last-child{
border-bottom:none;
}
</style>
</head>
<body>
<ul id="list">
<li>查看</li>
<li>删除</li>
<li>复制</li>
<li>粘贴</li>
</ul>
<script>
var list = document.getElementById('list');
/*
1.阻止默认事件
2.添加自己的事件,自定义菜单
*/
// 右键事件 oncontextmenu
document.oncontextmenu = function(ev){
var eve = event || ev;
eve.preventDefault(); // 阻止默认行为
list.style.display = 'block';
list.style.left = eve.clientX + 'px';
list.style.top = eve.clientY + 'px';
}
// 左键事件
document.onclick = function(){
list.style.display = 'none';
}
</script>
</body>
</html>
效果