右键菜单实例
<!doctype html> <html> <head> <!--声明当前页面的编码集:charset=gbk,gb2312(中文编码),utf-8国际编码--> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!--当前页面的三要素--> <title>右键菜单</title> <meta name="Keywords" content="关键词,关键词"> <meta name="description" content=""> <link rel="shortcut icon" href="p_w_picpaths/pifu2.jpg"> <!--css,js--> <style type="text/css"> *{margin:0;padding:0;} img{border:0;} body{font-size:12px;font-family:"微软雅黑";color:#666;background:url("p_w_picpaths/pifu2.jpg") no-repeat;} /*menu start*/ #menu{width:200px;background:#fff;box-shadow:1px 1px 30px #ccc;display:none;position:absolute;top:0;left:0; } #menu ul li{height:36px;line-height:36px;border-bottom:1px solid #ddd;padding-left:10px;list-style:none;font-size:14px;font-weight:500;} #menu ul li:hover{background:#666;color:#fff;} /*end start*/ </style> </head> <body> <!--menu start--> <div id="menu"> <ul> <li >添加应用</li> <li >获取课程</li> <li >添加笔记</li> <li >刷新</li> <li >上传资料</li> <li >更换背景</li> <li >注销</li> </ul> </div> <!--end menu--> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript"> // 屏蔽浏览器自带的右键 document.oncontextmenu = function(){ return false; } //鼠标键按下监控 $(document).mousedown(function(e){ //获取鼠标按下的键值 var key = e.which; if(key == 3){ //获取当前鼠标光标的坐标 var x = e.clientX; var y = e.clientY; //获取弹出菜单的宽度和高度 var menuwidth=$("#menu").width(); var menuheight=$("#menu").height(); //alert(menuwidth+"===========>>"+menuheight); //获取浏览器可视宽度和高度 var clientHeight=getClientHeight(); var clientWidth=getClientWidth(); //判断当光标靠边时,防止弹出菜单溢出浏览器可视范围 if((x+menuwidth)>clientWidth){x=clientWidth-menuwidth-10;} if((y+menuheight)>clientHeight){y=clientHeight-menuheight-10;} //为menu菜单定位 $("#menu").show().css({top:y,left:x}); } }); //鼠标点击任意浏览器区域菜单消失 $(document).click(function(){ //alert(0); $("#menu").hide(); }); // 浏览器的可见高度 function getClientHeight() { var clientHeight = 0; if (document.body.clientHeight && document.documentElement.clientHeight) { clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight: document.documentElement.clientHeight; } else { clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight: document.documentElement.clientHeight; } return clientHeight; } // 浏览器的可见宽度 function getClientWidth() { var clientWidth = 0; if (document.body.clientWidth && document.documentElement.clientWidth) { clientWidth = (document.body.clientWidth < document.documentElement.clientWidth) ? document.body.clientWidth: document.documentElement.clientWidth; } else { clientWidth = (document.body.clientWidth > document.documentElement.clientWidth) ? document.body.clientWidth: document.documentElement.clientWidth; } return clientWidth; } //鼠标点击菜单选项添加事件 $("#menu li").click(function(){ var li_index=$(this).index(); alert($(this).text()); }); </script> </body> </html>