jq自定义鼠标右键菜单

时间:2021-11-24 17:07:54

效果:

jq自定义鼠标右键菜单

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="test/datatables/jquery-1.10.2.js"></script>
<style>
*{
padding:0;
margin:0;
}
.button{
width:200px;
height:50px;
background:grey;
text-align:center;
line-height:50px;
margin:0 auto;
margin-top:50px;
}
.menu{
padding: 1px;
border: 1px solid #B8CBCB;
background-color: #fff;
-moz-box-shadow: 2px 2px 5px #666;
-webkit-box-shadow: 2px 2px 5px #666;
box-shadow: 2px 2px 5px #666;
width:140px;
position:absolute;
display:none;
}
ul li{
list-style:none;
}
.li_separate{
line-height: 0;
margin: 3px;
border-bottom: 1px solid #B8CBCB;
font-size: 0;
}
.menu_a{
display: block;
height: 25px;
line-height: 24px;
padding: 0 5px 0 25px;
color: #000;
font-size: 12px;
text-decoration: none;
}
.menu_a:hover{
background: #348CCC;
color:white;
}
</style>
</head>
<body>
<div class="button">点击</div>
<div class="menu">
<ul>
<li><a href="javascript:;" class="menu_a">复制</a></li>
<li><a href="javascript:;" class="menu_a">粘贴</a></li>
<li class="li_separate"></li>
<li><a href="javascript:;" class="menu_a">删除</a></li>
</ul>
</div>
<script>
//屏蔽浏览器右键菜单
document.oncontextmenu=function(){
return false;
}
$('.button').on('mousedown',function(e){
var key=e.which;//获取鼠标键位
if(key==3){//1:代表左键;2:代表中键;3:代表右键
//获取右键点击坐标
var x=e.clientX;
var y=e.clientY;
$('.menu').show().css({left:x,top:y});
}
})
//点击任意部位隐藏
$(document).on('click',function(){
$('.menu').hide();
})
</script>
</body>
</html>