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

Reg*_*ser 273 javascript contextmenu right-click

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

我的目标是Google Docs的功能.它允许用户右键单击并向用户显示他们自己的菜单.

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

Rad*_*kel 239

回答你的问题 - 使用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;
  });
}
Run Code Online (Sandbox Code Playgroud)

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


的jsfiddle

  • 您刚刚解释了如何禁用右键单击菜单.如何创建自己的菜单? (42认同)
  • 测试了Opera 11.01,Firefox 3.6.13,Chrome 9,Safari 5(所有4个通过addEventListener)和IE 8(attachEvent). (12认同)
  • @Shashwat你知道用户点击的地方,你没有原始菜单.在该位置创建一个容器并在那里显示您的菜单. (10认同)
  • _“但您应该问问自己,您真的要覆盖默认的右键单击行为吗?”_ -- 此解决方案与@MohamedIqzas (http://stackoverflow.com/ a/16481062/264097)。在下面的答案中,默认上下文菜单仅针对某个 HTML 元素被抑制,而不是针对整个文档。这使得它的侵入性小得多。 (5认同)
  • @shanehoban当你查看代码时,你会看到这行`e.preventDefault();`.这就是为什么不显示常规菜单的原因.你可以做的是创建一些条件逻辑来检查,如果在按下键的同时右键单击然后不调用`e.preventDefault()` - 那么你将获得常规的浏览器菜单. (3认同)
  • 跨浏览器兼容吗? (2认同)
  • 这是正确的:https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener Document也是一个元素. (2认同)

小智 48

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

HTML: contextmenu.html

$(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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

  • @Schism将`mouseY(event)`和`mouseX(event)`与`px`结合使其按预期工作:[http://jsfiddle.net/a6w7n64o/](http://jsfiddle.net/a6w7n64o/ ). (7认同)
  • 在firefox 39中,默认的contextmenu仍显示在自定义菜单的顶部.此外,自定义菜单在显示后立即消失. (6认同)
  • 你是通过`test`的id引用一个元素,但是`test`的id没有元素.只有`test`类的元素. (3认同)

Isa*_*aac 22

一些不错的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>
Run Code Online (Sandbox Code Playgroud)

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

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";
}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

另外请注意,您可以修改可能menu > menu{left:100%;}menu > menu{right:100%;}为从右到左展开菜单.您需要在某处添加边距或某些内容

  • 您可能需要在处理“contextmenu”事件的函数末尾添加“return false;”以支持更多浏览器(版本)。 (2认同)

by0*_*by0 12

您可以尝试通过在body标签中添加以下内容来阻止上下文菜单:

<body oncontextmenu="return false;">
Run Code Online (Sandbox Code Playgroud)

这将阻止对上下文菜单的所有访问(不仅来自鼠标右键,还来自键盘).

PS你可以将它添加到你要禁用上下文菜单的任何标签上

例如:

<div class="mydiv" oncontextmenu="return false;">
Run Code Online (Sandbox Code Playgroud)

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


Ste*_*sic 12

根据这里和其他流程的答案,我制作了一个看起来像谷歌Chrome的版本,css3过渡. JS Fiddle

让我们开始说话,因为我们在这个页面上面有js,我们可以担心css和布局.我们将使用的布局是一个<a>元素,带有<img>元素或字体awesome icon(<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>
Run Code Online (Sandbox Code Playgroud)

我们将这些放在div中并在右键单击时显示div.让我们像在Google Chrome中一样设计它们,好吗?

#menu a {
  display: block;
  color: #555;
  text-decoration: no[...]
Run Code Online (Sandbox Code Playgroud)

现在我们将从接受的答案中添加代码,并获取光标的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[...]
Run Code Online (Sandbox Code Playgroud)

就是这样!只需添加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";
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 当您右键单击页面的右侧部分时,菜单的某些部分会隐藏。 (3认同)
  • 这让我非常头疼!如果OP正在寻找一种在整个网页上使用的简单方法,而不仅仅是一个div,那么这应该被接受:) (2认同)

Yor*_*iev 11

纯 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())
  }
}
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<!-- 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>
Run Code Online (Sandbox Code Playgroud)


NVR*_*VRM 11

最简单的跳转启动功能,在光标位置创建一个上下文菜单,在鼠标离开时自行销毁。

oncontextmenu = (e) => {
  e.preventDefault()
  let menu = document.createElement("div")
  menu.id = "ctxmenu"
  menu.style = `top:${e.pageY-10}px;left:${e.pageX-40}px`
  menu.onmouseleave = () => ctxmenu.outerHTML = ''
  menu.innerHTML = "<p>Option1</p><p>Option2</p><p>Option3</p><p>Option4</p><p onclick='alert(`Thank you!`)'>Upvote</p>"
  document.body.appendChild(menu)
}
Run Code Online (Sandbox Code Playgroud)
#ctxmenu {
  position: fixed;
  background:ghostwhite;
  color: black;
  cursor: pointer;
  border: 1px black solid
}

#ctxmenu > p {
  padding: 0 1rem;
  margin: 0
}

#ctxmenu > p:hover {
  background: black;
  color: ghostwhite
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的解决方案,但如果双击就会出现问题! (2认同)

小智 10

<!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>
Run Code Online (Sandbox Code Playgroud)

测试并在Opera 11.6,firefox 9.01,Internet Explorer 9和chrome 17中工作.您可以在javascript右键菜单中查看工作示例

  • 如果您使用的是三键鼠标,它可以正常工作.按住Ctrl键单击使用户保持高位且干燥.@Singles有一个更好的建议,即使它确实留下了想象力. (2认同)

Gia*_*dei 9

尝试这个:

var cls = true;
var ops;

window.onload = function() {
    document.querySelector(".container").addEventListener("mouseenter", function() {
        cls = false;
    });
    document.querySelector(".container").addEventListener("mouseleave", function() {
        cls = true;
    });
    ops = document.querySelectorAll(".container td");
    for (let i = 0; i < ops.length; i++) {
        ops[i].addEventListener("click", function() {
            document.querySelector(".position").style.display = "none";
        });
    }

    ops[0].addEventListener("click", function() {
        setTimeout(function() {
            /* YOUR FUNCTION */
            alert("Alert 1!");
        }, 50);
    });

    ops[1].addEventListener("click", function() {
        setTimeout(function() {
            /* YOUR FUNCTION */
            alert("Alert 2!");
        }, 50);
    });

    ops[2].addEventListener("click", function() {
        setTimeout(function() {
            /* YOUR FUNCTION */
            alert("Alert 3!");
        }, 50);
    });

    ops[3].addEventListener("click", function() {
        setTimeout(function() {
            /* YOUR FUNCTION */
            alert("Alert 4!");
        }, 50);
    });

    ops[4].addEventListener("click", function() {
        setTimeout(function() {
            /* YOUR FUNCTION */
            alert("Alert 5!");
        }, 50);
    });
}

document.addEventListener("contextmenu", function() {
    var e = window.event;
    e.preventDefault();
    document.querySelector(".container").style.padding = "0px";

    var x = e.clientX;
    var y = e.clientY;

    var docX = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || document.body.offsetWidth;
    var docY = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || document.body.offsetHeight;

    var border = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('border-width'));

    var objX = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('width')) + 2;
    var objY = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('height')) + 2;

    if (x + objX > docX) {
        let diff = (x + objX) - docX;
        x -= diff + border;
    }

    if (y + objY > docY) {
        let diff = (y + objY) - docY;
        y -= diff + border;
    }

    document.querySelector(".position").style.display = "block";

    document.querySelector(".position").style.top = y + "px";
    document.querySelector(".position").style.left = x + "px";
});

window.addEventListener("resize", function() {
    document.querySelector(".position").style.display = "none";
});

document.addEventListener("click", function() {
    if (cls) {
        document.querySelector(".position").style.display = "none";
    }
});

document.addEventListener("wheel", function() {
    if (cls) {
        document.querySelector(".position").style.display = "none";
        static = false;
    }
});
Run Code Online (Sandbox Code Playgroud)
.position {
    position: absolute;
    width: 1px;
    height: 1px;
    z-index: 2;
    display: none;
}

.container {
    width: 220px;
    height: auto;
    border: 1px solid black;
    background: rgb(245, 243, 243);
}

.container p {
    height: 30px;
    font-size: 18px;
    font-family: arial;
    width: 99%;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgb(245, 243, 243);
    color: black;
    transition: 0.2s;
}

.container p:hover {
    background: lightblue;
}

td {
    font-family: arial;
    font-size: 20px;
}

td:hover {
    background: lightblue;
    transition: 0.2s;
    cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)
<div class="position">
    <div class="container" align="center">
        <table style="text-align: left; width: 99%; margin-left: auto; margin-right: auto;" border="0" cellpadding="2" cellspacing="2">
            <tbody>
                <tr>
                    <td style="vertical-align: middle; text-align: center;">Option 1<br>
                    </td>
                </tr>
                <tr>
                    <td style="vertical-align: middle; text-align: center;">Option 2<br>
                    </td>
                </tr>
                <tr>
                    <td style="vertical-align: middle; text-align: center;">Option 3<br>
                    </td>
                </tr>
                <tr>
                    <td style="vertical-align: middle; text-align: center;">Option 4<br>
                    </td>
                </tr>
                <tr>
                    <td style="vertical-align: middle; text-align: center;">Option 5<br>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 我想说这是最好的答案,因为它显示了一个实际的片段,您可以在其中看到当您选择不同选项时发生的操作。+1! (4认同)

For*_*ill 7

这是一个非常好的教程,介绍如何使用完整的工作代码示例(没有 JQuery 和其他库)构建自定义上下文菜单。

您还可以在 GitHub 上找到他们的演示代码

他们给出了详细的分步说明,您可以按照说明构建自己的右键单击上下文菜单(包括 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>
Run Code Online (Sandbox Code Playgroud)

可以在 codepen 上找到工作示例(任务列表)


小智 6

我知道这已经得到了解答,但我花了一些时间与第二个答案搏斗,让原生上下文菜单消失让它显示用户点击的位置.
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>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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";
});
Run Code Online (Sandbox Code Playgroud)

CodePen示例


Aks*_*kar 5

试试这个

$(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");           
 });
}
});
Run Code Online (Sandbox Code Playgroud)

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