右键菜单是固定的,很多时候,我们需要自定义web页面自定义菜单,指定相应的功能。
自定义的原理是:jQuery封装了鼠标右键的点击事件(“contextmenu”),首先屏蔽浏览器原始的点击事件,接着,写自己的需要的显示的右键菜单最后,就是什么时候隐藏显示出的右键菜单了。
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script> <title>jQuery制作Web页面鼠标右键美化菜单</title> <style type="text/css"> body{ position:relative;} ul,li{ margin:0; padding:0; list-style:none; font-size:12px;} .split{border-bottom: 1px solid gray;} .popup_menu{position:absolute; z-index:90; border:1px solid #AEAEAE; padding:2px; width:120px;border-radius: 2px;} .popup_menu a{ display:block; color:#325B8E; text-indent:12px; text-decoration:none; height:26px; line-height:25px; padding-right:5px;} .popup_menu a:hover{ background:#57B4E4; color:#fff; border-radius: 2px;} </style> </head> <body> <script type="text/javascript"> var kyPopupMenu={}; kyPopupMenu = (function(){ return { right: function (obj) { $(‘.popup_menu‘).remove(); var menu = ‘<div class="popup_menu app-menu"><ul><li><a url="http://www.cnblogs.com/mini-firework/">firework</a></li><li class="split"></li><li><a url="http://blog.csdn.net/e_real">疯狂的土豆专栏</a></li><li><a url="http://blog.163.com/qiuyg_yc_it/">网易博客</a></li></ul></div>‘; popupMenuApp = $(menu) .find(‘a‘).attr(‘href‘,‘javascript:;‘) .end().appendTo(‘body‘); //绑定事件 $(‘.app-menu a‘).on(‘click‘, function (){ window.location.href=$(this).attr("url"); }); return popupMenuApp; } }; })(); //取消右键 $(‘html‘).on(‘contextmenu‘, function (){return false;}).click(function(){ $(‘.popup_menu‘).hide(); }); //桌面点击右击 $(‘html‘).on(‘contextmenu‘,function (e){ var popupmenu = kyPopupMenu.right(); l = ($(document).width() - e.clientX) < popupmenu.width() ? (e.clientX - popupmenu.width()) : e.clientX; t = ($(document).height() - e.clientY) < popupmenu.height() ? (e.clientY - popupmenu.height()) : e.clientY; popupmenu.css({left: l,top: t}).show(); return false; }); </script> </body> </html>
效果展示:
时间: 2024-11-08 18:26:20