![](file:///C:/Users/ADMINI~1/AppData/Local/Temp/enhtmlclip/GIF(5).gif)
![](https://images2018.cnblogs.com/blog/1430556/201808/1430556-20180814180517426-187530818.gif)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义右键菜单</title> <style> body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td{ margin: 0; padding: 0; } body{ font-family:"Mrcrosoft Yahei",Arial; } ul,ol{ list-style: none; } a{ text-decoration: none; } img{ border:none; } .menu{ 100px; background: #9ff; position: absolute; left: -100%; } .uls li{ border-bottom: 1px solid black; padding: 5px 0 0 5px; border-right: 1px solid black; border-left: 1px solid black; } .uls li:hover{ background:#f9f ; } .uls li:hover a{ color:#ff9 ; } .uls li:first-child{ border-top: 1px solid black; } .uls a{ display: block; } </style> </head> <body> <!-- 书写自定义菜单样式 --> <div class="menu"> <ul class="uls"> <li><a href="数码时钟.html">数码时钟</a></li> <li><a href="留言板.html">留言板</a></li> <li><a href="进度条.html">进度条</a></li> <li><a href="随机生成二维码.html">二维码</a></li> <li><a href="吸顶效果.html">吸顶效果</a></li> <li><a href="隔行换色.html">隔行换色</a></li> </ul> </div> <script> //严格模式 'use strict'; //创建一个方法解决获取类名时的兼容性问题 function byClassName(sClassName){ if(document.getElementsByClassName){ return document.getElementsByClassName(sClassName); }else{ 找到所有的元素 var allTagName = document.getElementsByTagName('*'); // 然后遍历 var result = []; for(var i = 0;i < allTagName.length; i++){ // 因为一个页面中可能存在多个相同类名 if(allTagName[i].className ==sClassName){ result.push(allTagName[i]); } }return result; } } var oMenu = byClassName('menu')[0]; document.oncontextmenu = function(ev){ // 获取事件对象 var e = ev || window.event; var iL = e.clientX, iT = e.clientY; oMenu.style.left = iL + 'px'; oMenu.style.top = iT + 'px'; // 当点击浏览器任意地方时,让菜单消失 document.onclick = function(){ oMenu.style.left = '-100%'; } //阻止浏览器的默认行为 return false; } </script> </body> </html>