如何将自定义右键单击菜单添加到网页?

我想添加一个自定义的右键菜单到我的Web应用程序。 这可以做到不使用任何预build的库? 如果是这样,如何显示一个简单的不使用第三方JavaScript库的自定义右键菜单?

我正在瞄准像Google Docs那样的东西。 它让用户右键单击并显示用户自己的菜单。

注:我想学习如何使自己与使用某人已经做的东西,因为大多数时候,这些第三方库臃肿的function,而我只想要的function,我需要,所以我希望它是完全手工制作的我。

回答你的问题 – 使用contextmenu事件,如下所示:

 <html> <head> <script type="text/javascript"> if (document.addEventListener) { // IE >= 9; other browsers document.addEventListener('contextmenu', function(e) { alert("You've tried to open context menu"); //here you draw your own menu e.preventDefault(); }, false); } else { // IE < 9 document.attachEvent('oncontextmenu', function() { alert("You've tried to open context menu"); window.event.returnValue = false; }); } </script> </head> <body> Lorem ipsum... </body> </html> 

但是你应该问自己,你真的想覆盖默认的右键单击行为 – 这取决于你正在开发的应用程序。


的jsfiddle

对我来说非常有用 为了像我这样的人,期待菜单的绘制,我在这里把我用来做右键菜单的代码放在这里:

HTMLcontextmenu.html

 <!doctype html> <html> <head> <!-- jQuery should be at least version 1.7 --> <script src="jquery-1.11.0.min.js"></script> <script src="contextmenu.js"></script> <link rel="stylesheet" href="contextmenu.css" /> </head> <body> <div id="test1"> <a href="www.google.com" class="test">Google</a> <a href="www.google.com" class="test">Link 2</a> <a href="www.google.com" class="test">Link 3</a> <a href="www.google.com" class="test">Link 4</a> </div> <!-- initially hidden right-click menu --> <div class="hide" id="rmenu"> <ul> <li> <a href="http://www.google.com">Google</a> </li> <li> <a href="http://localhost:8080/login">Localhost</a> </li> <li> <a href="C:\">C</a> </li> </ul> </div> </body> </html> 

CSS: contextmenu.css

 .show { z-index:1000; position: absolute; background-color:#C0C0C0; border: 1px solid blue; padding: 2px; display: block; margin: 0; list-style-type: none; list-style: none; } .hide { display: none; } .show li{ list-style: none; } .show a { border: 0 !important; text-decoration: none; } .show a:hover { text-decoration: underline !important; } 

JS: contextmenu.js – 从接受的答案中使用

 $(document).ready(function() { if ($("#test").addEventListener) { $("#test").addEventListener('contextmenu', function(e) { alert("You've tried to open context menu"); //here you draw your own menu e.preventDefault(); }, false); } else { //document.getElementById("test").attachEvent('oncontextmenu', function() { //$(".test").bind('contextmenu', function() { $('body').on('contextmenu', 'a.test', function() { //alert("contextmenu"+event); document.getElementById("rmenu").className = "show"; document.getElementById("rmenu").style.top = mouseY(event) + 'px'; document.getElementById("rmenu").style.left = mouseX(event) + 'px'; window.event.returnValue = false; }); } }); // this is from another SO post... $(document).bind("click", function(event) { document.getElementById("rmenu").className = "hide"; }); function mouseX(evt) { if (evt.pageX) { return evt.pageX; } else if (evt.clientX) { return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); } else { return null; } } function mouseY(evt) { if (evt.pageY) { return evt.pageY; } else if (evt.clientY) { return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); } else { return null; } } 
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <head> <title>Context menu - LabLogic.net</title> </head> <body> <script language="javascript" type="text/javascript"> document.oncontextmenu=RightMouseDown; document.onmousedown = mouseDown; function mouseDown(e) { if (e.which==3) {//righClick alert("Right-click menu goes here"); } } function RightMouseDown() { return false; } </script> </body> </html> 

经过testing,并在Opera 11.6,Firefox 9.01,Internet Explorer 9和Chrome 17中工作您可以在javascript右键菜单中查看正在运行的示例

您可以尝试简单地通过将以下内容添加到您的身体标记来阻止上下文菜单:

 <body oncontextmenu="return false;"> 

这将阻止对上下文菜单的所有访问(不仅仅是从鼠标右键,而是从键盘)。

PS,你可以添加到任何你想禁用上下文菜单的标签

例如:

 <div class="mydiv" oncontextmenu="return false;"> 

将只禁用该特定的div中的上下文菜单

一些不错的CSS和一些非标准的html标签,没有外部库的组合可以给一个不错的结果(JSFiddle)

HTML

 <menu id="ctxMenu"> <menu title="File"> <menu title="Save"></menu> <menu title="Save As"></menu> <menu title="Open"></menu> </menu> <menu title="Edit"> <menu title="Cut"></menu> <menu title="Copy"></menu> <menu title="Paste"></menu> </menu> </menu> 

注意:菜单标签不存在,我正在做(你可以使用任何东西)

CSS

 #ctxMenu{ display:none; z-index:100; } menu { position:absolute; display:block; left:0px; top:0px; height:20px; width:20px; padding:0; margin:0; border:1px solid; background-color:white; font-weight:normal; white-space:nowrap; } menu:hover{ background-color:#eef; font-weight:bold; } menu:hover > menu{ display:block; } menu > menu{ display:none; position:relative; top:-20px; left:100%; width:55px; } menu[title]:before{ content:attr(title); } menu:not([title]):before{ content:"\2630"; } 

JavaScript只是为了这个例子,我个人删除它在Windows上的持久性菜单

 var notepad = document.getElementById("notepad"); notepad.addEventListener("contextmenu",function(event){ event.preventDefault(); var ctxMenu = document.getElementById("ctxMenu"); ctxMenu.style.display = "block"; ctxMenu.style.left = (event.pageX - 10)+"px"; ctxMenu.style.top = (event.pageY - 10)+"px"; },false); notepad.addEventListener("click",function(event){ var ctxMenu = document.getElementById("ctxMenu"); ctxMenu.style.display = ""; ctxMenu.style.left = ""; ctxMenu.style.top = ""; },false); 

另请注意,您可以修改menu > menu{left:100%;}menu > menu{right:100%;} ,从右向左扩展菜单。 您将需要添加一个保证金或某个地方

尝试这个

 $(function() { var doubleClicked = false; $(document).on("contextmenu", function (e) { if(doubleClicked == false) { e.preventDefault(); // To prevent the default context menu. var windowHeight = $(window).height()/2; var windowWidth = $(window).width()/2; if(e.clientY > windowHeight && e.clientX <= windowWidth) { $("#contextMenuContainer").css("left", e.clientX); $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY); $("#contextMenuContainer").css("right", "auto"); $("#contextMenuContainer").css("top", "auto"); } else if(e.clientY > windowHeight && e.clientX > windowWidth) { $("#contextMenuContainer").css("right", $(window).width()-e.clientX); $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY); $("#contextMenuContainer").css("left", "auto"); $("#contextMenuContainer").css("top", "auto"); } else if(e.clientY <= windowHeight && e.clientX <= windowWidth) { $("#contextMenuContainer").css("left", e.clientX); $("#contextMenuContainer").css("top", e.clientY); $("#contextMenuContainer").css("right", "auto"); $("#contextMenuContainer").css("bottom", "auto"); } else { $("#contextMenuContainer").css("right", $(window).width()-e.clientX); $("#contextMenuContainer").css("top", e.clientY); $("#contextMenuContainer").css("left", "auto"); $("#contextMenuContainer").css("bottom", "auto"); } $("#contextMenuContainer").fadeIn(500, FocusContextOut()); doubleClicked = true; } else { e.preventDefault(); doubleClicked = false; $("#contextMenuContainer").fadeOut(500); } }); function FocusContextOut() { $(document).on("click", function () { doubleClicked = false; $("#contextMenuContainer").fadeOut(500); $(document).off("click"); }); } }); 

http://jsfiddle.net/AkshayBandivadekar/zakn7​​Lwb/14/

根据这里和其他的答案,我做了一个看起来像谷歌浏览器,与css3过渡的版本。 JS小提琴

让我们开始eazy,因为我们有这个页面上面的js,我们可以担心css和布局。 我们将使用的布局是一个带有<img>元素或字体超赞图标( <i class="fa fa-flag"></i> )的<a>元素和一个用于显示键盘的<span>快捷键。 所以这是结构:

 <a href="#" onclick="doSomething()"> <img src="path/to/image.gif" /> This is a menu option <span>Ctrl + K</span> </a> 

我们将把它们放在一个div中,并在右键单击时显示div。 让我们在Google Chrome浏览器中进行devise,我们可以吗?

 #menu a { display: block; color: #555; text-decoration: no[...] 

现在我们将添加接受答案中的代码,并获取游标的X和Y值。 为此,我们将使用e.clientXe.clientY 。 我们正在使用客户端,所以菜单div必须修复。

 var i = document.getElementById("menu").style; if (document.addEventListener) { document.addEventListener('contextmenu', function(e) { var posX = e.clientX; var posY = e.client[...] 

就是这样! 只需添加CSS转换淡入淡出,完成!

 var i = document.getElementById("menu").style; if (document.addEventListener) { document.addEventListener('contextmenu', function(e) { var posX = e.clientX; var posY = e.clientY; menu(posX, posY); e.preventDefault(); }, false); document.addEventListener('click', function(e) { i.opacity = "0"; setTimeout(function() { i.visibility = "hidden"; }, 501); }, false); } else { document.attachEvent('oncontextmenu', function(e) { var posX = e.clientX; var posY = e.clientY; menu(posX, posY); e.preventDefault(); }); document.attachEvent('onclick', function(e) { i.opacity = "0"; setTimeout(function() { i.visibility = "hidden"; }, 501); }); } function menu(x, y) { i.top = y + "px"; i.left = x + "px"; i.visibility = "visible"; i.opacity = "1"; } 
 body { background: white; font-family: sans-serif; color: #5e5e5e; } #menu { visibility: hidden; opacity: 0; position: fixed; background: #fff; color: #555; font-family: sans-serif; font-size: 11px; -webkit-transition: opacity .5s ease-in-out; -moz-transition: opacity .5s ease-in-out; -ms-transition: opacity .5s ease-in-out; -o-transition: opacity .5s ease-in-out; transition: opacity .5s ease-in-out; -webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1); -moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1); box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1); padding: 0px; border: 1px solid #C6C6C6; } #menu a { display: block; color: #555; text-decoration: none; padding: 6px 8px 6px 30px; width: 250px; position: relative; } #menu a img, #menu a i.fa { height: 20px; font-size: 17px; width: 20px; position: absolute; left: 5px; top: 2px; } #menu a span { color: #BCB1B3; float: right; } #menu a:hover { color: #fff; background: #3879D9; } #menu hr { border: 1px solid #EBEBEB; border-bottom: 0; } 
 <link href="font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/> <h2>CSS3 and JAVASCRIPT custom menu.</h2> <em>Stephan Stanisic | Lisence free</em> <p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p> <p style="font-size: small"> <b>Lisence</b> <br /> "THE PIZZA-WARE LICENSE" (Revision 42): <br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return. <br /> <a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a> </p> <br /> <br /> <small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small> <div id="menu"> <a href="#"> <img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span> </a> <a href="#"> <img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span> </a> <hr /> <a href="#"> <i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span> </a> <a href="#"> <i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span> </a> </div> 

我知道这已经得到了回答,但我花了一些时间与第二个答案摔跤得到本地上下文菜单消失并显示在用户点击的地方。
HTML

 <body> <div id="test1"> <a href="www.google.com" class="test">Google</a> <a href="www.google.com" class="test">Link 2</a> <a href="www.google.com" class="test">Link 3</a> <a href="www.google.com" class="test">Link 4</a> </div> <!-- initially hidden right-click menu --> <div class="hide" id="rmenu"> <ul> <li class="White">White</li> <li>Green</li> <li>Yellow</li> <li>Orange</li> <li>Red</li> <li>Blue</li> </ul> </div> </body> 

CSS

 .hide { display: none; } #rmenu { border: 1px solid black; background-color: white; } #rmenu ul { padding: 0; list-style: none; } #rmenu li { list-style: none; padding-left: 5px; padding-right: 5px; } 

JavaScript的

 if (document.getElementById('test1').addEventListener) { document.getElementById('test1').addEventListener('contextmenu', function(e) { $("#rmenu").toggleClass("hide"); $("#rmenu").css( { position: "absolute", top: e.pageY, left: e.pageX } ); e.preventDefault(); }, false); } // this is from another SO post... $(document).bind("click", function(event) { document.getElementById("rmenu").className = "hide"; }); 

CodePen示例

你可以用这个代码来做。 请访问此处以获取有关自动边缘检测的完整教程http://www.voidtricks.com/custom-right-click-context-menu/

 $(document).ready(function () { $("html").on("contextmenu",function(e){ //prevent default context menu for right click e.preventDefault(); var menu = $(".menu"); //hide menu if already shown menu.hide(); //get x and y values of the click event var pageX = e.pageX; var pageY = e.pageY; //position menu div near mouse cliked area menu.css({top: pageY , left: pageX}); var mwidth = menu.width(); var mheight = menu.height(); var screenWidth = $(window).width(); var screenHeight = $(window).height(); //if window is scrolled var scrTop = $(window).scrollTop(); //if the menu is close to right edge of the window if(pageX+mwidth > screenWidth){ menu.css({left:pageX-mwidth}); } //if the menu is close to bottom edge of the window if(pageY+mheight > screenHeight+scrTop){ menu.css({top:pageY-mheight}); } //finally show the menu menu.show(); }); $("html").on("click", function(){ $(".menu").hide(); }); }); 

`

 <script language="javascript" type="text/javascript"> document.oncontextmenu = RightMouseDown; document.onmousedown = mouseDown; function mouseDown(e) { if (e.which==3) {//righClick alert("Right-click menu goes here"); } } function RightMouseDown() { return false; } </script> </body> </html> 

一个简单的方法是使用onContextMenu来返回一个JavaScript函数:

 <input type="button" value="Example" onContextMenu="return RightClickFunction();"> <script> function RightClickFunction() { // Enter your code here; return false; } </script> 

并通过inputreturn false; 您将取消上下文菜单。

如果你仍然想显示上下文菜单,你可以删除return false; 线。

经过testing,在Opera 12.17,firefox 30,Internet Explorer 9和Chrome 26.0.1410.64上运行

 document.oncontextmenu =function( evt ){ alert("OK?"); return false; } 

这里是一个关于如何构build一个完整的工作代码示例(没有JQuery和其他库) 的自定义上下文菜单非常好的教程 。

你也可以在GitHub上find他们的演示代码 。

他们给出了详细的一步一步的解释,你可以按照自己的右键单击上下文菜单(包括HTML,CSS和JavaScript代码),并在最后给出完整的示例代码总结它。

你可以很容易地跟随和适应你自己的需求。 而且不需要JQuery或其他库。

这是他们的示例菜单代码的样子:

 <nav id="context-menu" class="context-menu"> <ul class="context-menu__items"> <li class="context-menu__item"> <a href="#" class="context-menu__link" data-action="View"><i class="fa fa-eye"></i> View Task</a> </li> <li class="context-menu__item"> <a href="#" class="context-menu__link" data-action="Edit"><i class="fa fa-edit"></i> Edit Task</a> </li> <li class="context-menu__item"> <a href="#" class="context-menu__link" data-action="Delete"><i class="fa fa-times"></i> Delete Task</a> </li> </ul> </nav> 

一个工作示例(任务列表)可以在codepen上find 。

在新的HTML 5.1中,有一个新的上下文菜单function。

示例在这里

 IMPORTANT: ATM, This feature works only in Firefox 49 and later. 

你应该记住,如果你想使用Firefox的唯一的解决scheme,如果你想把它添加到整个文档,你应该添加contextmenu="mymenu"<html>标签而不是body标签。
你应该注意这一点。

您可能应该使用第三方UI小部件。

我推荐Shield UI的上下文菜单 ,这是一个灵活的,易于集成的JavaScript和HTML5组件。

就在今天,我发现了另外两个很好的例子(我想):

DEMO 1 // DEMO 2 (这个演示需要jQuery UI

我希望对任何人有所帮助,bb。

 <html> <head> <style> .rightclick { /* YOUR CONTEXTMENU'S CSS */ visibility: hidden; background-color: white; border: 1px solid grey; width: 200px; height: 300px; } </style> </head> <body> <div class="rightclick" id="ya"> <p onclick="alert('choc-a-late')">I like chocolate</p><br><p onclick="awe-so-me">I AM AWESOME</p> </div> <p>Right click to get sweet results!</p> </body> <script> document.onclick = noClick; document.oncontextmenu = rightClick; function rightClick(e) { e = e || window.event; e.preventDefault(); document.getElementById("ya").style.visibility = "visible"; console.log("Context Menu v1.3.0 by IamGuest opened."); } function noClick() { document.getElementById("ya").style.visibility = "hidden"; console.log("Context Menu v1.3.0 by IamGuest closed."); } </script> <!-- Coded by IamGuest. Thank you for using this code! --> </html> 

你可以调整和修改这个代码,使一个更好看,更有效的contextmenu。 至于修改现有的contextmenu,我不知道该怎么做…检查出这个小提琴有组织的观点。 另外,请尝试点击我的上下文菜单中的项目。 他们应该提醒你一些很棒的信息。 如果他们不工作,尝试一些更复杂的东西。

 <script> function fun(){ document.getElementById('menu').style.display="block"; } </script> <div id="menu" style="display: none"> menu items</div> <body oncontextmenu="fun();return false;"> 

我在这里做什么

  1. 创build自己的自定义div菜单,并设置位置:绝对和显示:无以防万一。
  2. 添加到要点击oncontextmenu事件的页面或元素。
  3. 取消默认的浏览器操作返回false。
  4. 用户js调用您自己的操作。

Interesting Posts