js自定义右键菜单

版权声明:原创文章,未经允许不得转载!!! https://blog.csdn.net/halo1416/article/details/82824577

前言:现在的网页基本都是有右键菜单的,类似于:

(来自于Chrome任务网页,“捕捉网页截图 - FireShot的” 是安装的一个插件);

但是,我们有时候可以在一些网站上看到不一样的右键菜单即自定义右键菜单,如腾讯企业邮箱网页版:

今天,记录一些简单的右键菜单是怎么做的:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#rightMenu
			{
				list-style: none;
				background: gainsboro;
				border: solid 1px darkgrey;
				margin: 0px;
				padding: 5px;
				position: absolute;
				/*left: 0px;*/
				top: 0px;
				display: none;
			}
			#rightMenu li
			{
				border-bottom: solid 1px darkgrey;
			}
		</style>
	</head>
	<body>
		<ul id="rightMenu" style="width: 100px;">
			<li>新建</li>
			<li>打开</li>
			<li>保存</li>
			<li>关闭</li>
		</ul>
		<script type="text/javascript">
			//提取到函数外面作为全局变量
			var rm=document.getElementById("rightMenu");
			
			//自定义一个浏览器右键菜单,单击右键是显示它
			//oncontextmenu上下文菜单事件,右键菜单
			document.documentElement.oncontextmenu=function (e) {
				//显示我们自己定义的右键菜单
				//1.找到菜单
				//提取到函数外面作为全局变量
				
				//兼容Event对象
				e=e || window.event;
				
				//2.设置菜单的位置等于鼠标的坐标
				//判断:如果鼠标的位置+菜单的宽度>网页的宽度,那么就改为右边定位
				//鼠标坐标
				var mx=e.clientX;
				var my=e.clientY;
				//菜单宽度
				var rmWidth=parseInt(rm.style.width);
				//网页的宽度(高度用同样的方法解决)
				var pageWidth=document.documentElement.clientWidth;
				//console.log(pageWidth);
				if((mx+rmWidth)<pageWidth)
				{
					rm.style.left=mx+"px";
				    rm.style.top=my+"px";
				}
				else
				{
					rm.style.right=mx+"px";
				    rm.style.top=my+"px";
				}
				
				//3.显示右键菜单
				rm.style.display="block";
				
				//阻止默认的右键菜单显示
				return false;
			};
			
			//不需要积隐藏右键菜单
			document.documentElement.onclick=function () {
				rm.style.display="none";
			}
		</script>
	</body>
</html>

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!

猜你喜欢

转载自blog.csdn.net/halo1416/article/details/82824577