js自定义右键

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41179401/article/details/81989593

js自定义右键

思路:1:阻止系统自带右键菜单:使用上下文事件contextmenu

           2:先将自定义菜单隐藏在触发上下文事件时显示自定义菜单;

           3:点击文档其它处隐藏菜单

结果图示:

代码:html:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>表单</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script type="text/javascript" src="index.js"></script>
</head>
<body>
	<p id="box">测试段落</p>
	<div id="menu">
		<ul>
			<li><a href="#">分享</a></li>
			<li><a href="#">收藏</a></li>
			<li><a href="#">举报</a></li>
		</ul>
	</div>
</body>
</html>

css:

*{
	margin: 0;
	padding: 0;
}
p{
	margin-top: 200px;	
}
ul li{
	list-style-type: none;
	margin: 10px 0;
	text-align: center;
}
#menu{
	border:1px solid #ccc;
	background: #eee;
	position: absolute;
	width: 100px;
	height: 120px;
	display: none;
}

javascript:

window.onload = function(){
	var p = document.getElementById('box');
	var menu = document.getElementById('menu');
	p.oncontextmenu = function(e){
		var e = e || window.event;
		e.preventDefault();            //阻止系统右键菜单 IE8-不支持
		// 显示自定义的菜单 调整位置
		menu.style.display = 'block';
		menu.style.left = e.clientX + 'px';
		menu.style.top = e.clientY + 'px';
	}
	// 鼠标点击其他位置时隐藏菜单
	document.onclick = function(){
		menu.style.display = 'none';     //隐藏菜单
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41179401/article/details/81989593