Javascript 如何向网页添加自定义右键单击菜单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4909167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a custom right-click menu to a webpage?
提问by Registered User
I want to add a custom right-click menu to my web application. Can this be done without using any pre-built libraries? If so, how to display a simple custom right-click menu which does not use a 3rd party JavaScript library?
我想向我的 Web 应用程序添加自定义右键单击菜单。这可以在不使用任何预建库的情况下完成吗?如果是这样,如何显示不使用 3rd 方 JavaScript 库的简单自定义右键单击菜单?
I'm aiming for something like what Google Docs does. It lets users right-click and show the users their own menu.
我的目标是类似于 Google Docs 的功能。它允许用户右键单击并向用户显示他们自己的菜单。
NOTE:I want to learn how to make my own versus using something somebody made already since most of the time, those 3rd party libraries are bloated with features whereas I only want features that I need so I want it to be completely hand-made by me.
注意:我想学习如何制作我自己的东西而不是使用别人已经制作的东西,因为大多数时候,那些 3rd 方库的功能很臃肿,而我只想要我需要的功能,所以我希望它完全手工制作我。
采纳答案by Radek Benkel
Answering your question - use contextmenu
event, like below:
回答您的问题 - 使用contextmenu
事件,如下所示:
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
alert("You've tried to open context menu"); //here you draw your own menu
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
alert("You've tried to open context menu");
window.event.returnValue = false;
});
}
<body>
Lorem ipsum...
</body>
But you should ask yourself, do you really want to overwrite default right-click behavior - it depends on application that you're developing.
但是您应该问问自己,您是否真的要覆盖默认的右键单击行为 - 这取决于您正在开发的应用程序。
回答by Mohamed Iqzas
Was very useful for me. For the sake of people like me, expecting the drawing of menu, I put here the code I used to make the right-click menu:
对我非常有用。为了像我这样的人,期待菜单的绘制,我把我用来制作右键菜单的代码放在这里:
$(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;
}
}
.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;
}
<!-- jQuery should be at least version 1.7 -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="contextmenu.js"></script>
<link rel="stylesheet" href="contextmenu.css" />
<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>
回答by Isaac
A combination of some nice CSS and some non-standard html tags with no external libraries can give a nice result (JSFiddle)
一些漂亮的 CSS 和一些没有外部库的非标准 html 标签的组合可以产生很好的结果 (JSFiddle)
HTML
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>
Note: the menu tag does not exist, I'm making it up (you can use anything)
注意:菜单标签不存在,我自己编的(你可以用任何东西)
CSS
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:"30";
}
The JavaScriptis just for this example, I personally remove it for persistent menus on windows
在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);
Also note, you can potentially modify menu > menu{left:100%;}
to menu > menu{right:100%;}
for a menu that expands from right to left. You would need to add a margin or something somewhere though
另外请注意,您可以可能修改menu > menu{left:100%;}
,以menu > menu{right:100%;}
用于从右翼扩大到左边的菜单。您需要在某处添加边距或其他内容
回答by Stephan Stanisic
According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition. JS Fiddle
根据此处和其他“流程”中的答案,我制作了一个看起来像 Google Chrome 的版本,带有 css3 过渡。 JS Fiddle
Lets start eazy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an <a>
element with a <img>
element or a font awesome icon (<i class="fa fa-flag"></i>
) and a <span>
to show the keyboard shortcuts. So this is the structure:
让我们开始 eazy,因为我们在这个页面上有上面的 js,我们可以担心 css 和布局。我们将使用的布局是一个<a>
元素,带有一个<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>
We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?
我们将把它们放在一个 div 中,并在右键单击时显示该 div。让我们像在 Google Chrome 中一样设计它们,好吗?
#menu a {
display: block;
color: #555;
text-decoration: no[...]
Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use e.clientX
and e.clientY
. We are using client, so the menu div has to be fixed.
现在我们将从接受的答案中添加代码,并获取光标的 X 和 Y 值。为此,我们将使用e.clientX
和e.clientY
。我们正在使用客户端,因此必须修复菜单 div。
var i = document.getElementById("menu").style;
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
var posX = e.clientX;
var posY = e.client[...]
And that is it! Just add the css transisions to fade in and out, and done!
就是这样!只需添加 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="https://maxcdn.bootstrapcdn.com/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>
回答by by0
You could try simply blocking the context menu by adding the following to your body tag:
您可以尝试通过将以下内容添加到您的正文标签来简单地阻止上下文菜单:
<body oncontextmenu="return false;">
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).
这将阻止对上下文菜单的所有访问(不仅从鼠标右键,而且从键盘)。
P.S. you can add this to any tag you want to disable the context menu on
PS,您可以将此添加到要禁用上下文菜单的任何标签
for example:
例如:
<div class="mydiv" oncontextmenu="return false;">
Will disable the context menu in that particular div only
将仅禁用该特定 div 中的上下文菜单
回答by LabLogic
<!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>
Tested and works in Opera 11.6, firefox 9.01, Internet Explorer 9 and chrome 17 You can check out a working sample at javascript right click menu
在 Opera 11.6、firefox 9.01、Internet Explorer 9 和 chrome 17 中测试并运行您可以在javascript 右键菜单中查看工作示例
回答by Kristen Nielsen
I know this has already been answered, but I spent some time wrestling with the second answer to get the native context menu to disappear andhave it show up where the user clicked.
HTML
我知道这已经得到了回答,但是我花了一些时间来解决第二个答案,以使本机上下文菜单消失并显示在用户单击的位置。
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
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
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";
});
回答by AkshayBandivadekar
Try This
尝试这个
$(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");
});
}
});
回答by Yordan Georgiev
Pure JS and css solution for a truly dynamic right click context menu, albeit based on pre-defined naming conventions for the elements id, links etc. jsfiddleand the code you could copy paste into a single static html page :
纯 JS 和 css 解决方案,用于真正动态的右键单击上下文菜单,尽管基于元素 id、链接等的预定义命名约定。 jsfiddle和您可以复制粘贴到单个静态 html 页面的代码:
<html>
<head>
<style>
.cls-context-menu-link {
display:block;
padding:20px;
background:#ECECEC;
}
.cls-context-menu { position:absolute; display:none; }
.cls-context-menu ul, #context-menu li {
list-style:none;
margin:0; padding:0;
background:white;
}
.cls-context-menu { border:solid 1px #CCC;}
.cls-context-menu li { border-bottom:solid 1px #CCC; }
.cls-context-menu li:last-child { border:none; }
.cls-context-menu li a {
display:block;
padding:5px 10px;
text-decoration:none;
color:blue;
}
.cls-context-menu li a:hover {
background:blue;
color:#FFF;
}
</style>
</head>
<body>
<!-- those are the links which should present the dynamic context menu -->
<a id="link-1" href="#" class="cls-context-menu-link">right click link-01</a>
<a id="link-2" href="#" class="cls-context-menu-link">right click link-02</a>
<!-- this is the context menu -->
<!-- note the string to=0 where the 0 is the digit to be replaced -->
<div id="div-context-menu" class="cls-context-menu">
<ul>
<li><a href="#to=0">link-to=0 -item-1 </a></li>
<li><a href="#to=0">link-to=0 -item-2 </a></li>
<li><a href="#to=0">link-to=0 -item-3 </a></li>
</ul>
</div>
<script>
var rgtClickContextMenu = document.getElementById('div-context-menu');
/** close the right click context menu on click anywhere else in the page*/
document.onclick = function(e){
rgtClickContextMenu.style.display = 'none';
}
/**
present the right click context menu ONLY for the elements having the right class
by replacing the 0 or any digit after the "to-" string with the element id , which
triggered the event
*/
document.oncontextmenu = function(e){
//alert(e.target.id)
var elmnt = e.target
if ( elmnt.className.startsWith ( "cls-context-menu")) {
e.preventDefault();
var eid = elmnt.id.replace(/link-/,"")
rgtClickContextMenu.style.left = e.pageX + 'px'
rgtClickContextMenu.style.top = e.pageY + 'px'
rgtClickContextMenu.style.display = 'block'
var toRepl = "to=" + eid.toString()
rgtClickContextMenu.innerHTML = rgtClickContextMenu.innerHTML.replace(/to=\d+/g,toRepl)
//alert(rgtClickContextMenu.innerHTML.toString())
}
}
</script>
</body>
</html>
回答by ForceOfWill
Here is a very good tutorial on how to build a custom context menuwith a full working code example (without JQuery and other libraries).
这是一个关于如何使用完整的工作代码示例(没有 JQuery 和其他库)构建自定义上下文菜单的非常好的教程。
You can also find their demo code on GitHub.
您还可以在 GitHub 上找到他们的演示代码。
They give a detailed step-by-step explanation that you can follow along to build your own right-click context menu (including html, css and javascript code) and summarize it at the end by giving the complete example code.
他们提供了详细的分步说明,您可以按照这些说明构建自己的右键单击上下文菜单(包括 html、css 和 javascript 代码),并在最后通过提供完整的示例代码对其进行总结。
You can follow along easily and adapt it to your own needs. And there is no need for JQuery or other libraries.
您可以轻松遵循并根据自己的需要进行调整。并且不需要 JQuery 或其他库。
This is how their example menu code looks like:
这是他们的示例菜单代码的样子:
<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>