我想添加一个自定义右键菜单到我的web应用程序。这可以在不使用任何预先构建的库的情况下完成吗?如果是这样,如何显示一个简单的自定义右键菜单,不使用第三方JavaScript库?

我的目标是像谷歌Docs做的东西。它允许用户右键单击并显示用户自己的菜单。

注意: 我想学习如何制作我自己的,而不是使用别人已经制作的东西,因为大多数时候,那些第三方库的功能都很臃肿,而我只想要我需要的功能,所以我希望它完全由我手工制作。


当前回答

纯JS和css解决方案,一个真正的动态右键单击上下文菜单,尽管基于预定义的命名约定的元素id,链接等。 jsfiddle 你可以复制粘贴到单个静态HTML页面的代码:

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()) } } .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; } <!-- 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>

其他回答

根据这里和其他'流程的答案,我已经制作了一个看起来像谷歌Chrome的版本,带有css3过渡。 JS小提琴

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

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

我们将把这些放在一个div中,并在右键菜单中显示该div。让我们风格他们像在谷歌Chrome浏览器,好吗?

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

现在,我们将从接受的答案中添加代码,并获得游标的X和Y值。为此,我们将使用e.clientX和e. clienti。我们正在使用客户端,所以菜单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! 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>

<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>

您可以调整和修改这段代码,使上下文菜单看起来更美观、更高效。至于修改一个现有的上下文菜单,我不知道如何做到这一点…看看这把小提琴,有组织的观点。另外,试着点击我的上下文菜单中的项目。他们应该提醒你一些很棒的信息。如果它们不起作用,那就试试别的……复杂。

你可以用这段代码来做。 访问这里获得完整的自动边缘检测教程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();
 });
 });

`

纯JS和css解决方案,一个真正的动态右键单击上下文菜单,尽管基于预定义的命名约定的元素id,链接等。 jsfiddle 你可以复制粘贴到单个静态HTML页面的代码:

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()) } } .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; } <!-- 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>

我知道这个问题已经有了答案,但我花了一些时间来解决第二个答案,以使本机上下文菜单消失,并在用户单击的地方显示出来。 超文本标记语言

<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例子