如何使用 JavaScript 打开锚上下文菜单?

我正在尝试仅使用 JavaScript 打开锚点上下文菜单,例如对于此 HTML:


<html>

  <head></head>

  <body>

    <a href="https://stackoverflow.com" id="anchor-el"> Anchor </a>

  </body>

</html>

我想仅使用 JavaScript 打开带有本机“在链接新选项卡中打开”和“在新窗口中打开链接”选项的上下文菜单。


到目前为止我已经试过了,它似乎成功地contextmenu向锚点发送了一个事件,但上下文菜单实际上并没有显示......


document.getElementById('anchor-el').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }))


MMMHUHU
浏览 140回答 5
5回答

慕尼黑8549860

根据我对你的问题的理解,你希望用结果“替换”正常的click事件结果contextmenu......但是只有那个上下文菜单的前两个项目。这使它成为您必须定义的自定义菜单。所以这里有一些东西......let contextElements = document.querySelectorAll(".context-anchor")let myContext = document.querySelector(".context")let contextItems = document.querySelectorAll(".context-item")let contextHref// To add event a listener on each .context-anchor element in order to show a "simulated context menu"contextElements.forEach(function(ce){  ce.addEventListener("click", function(e){    e.preventDefault()        // Get the click coord to open the context menu at the right place    let clickCoords = {x: e.pageX, y: e.pageY}    // Get the href of the clicked link    contextHref = ce.href        // Create a mouse event    let event = document.createEvent('MouseEvents');    event.initEvent('mycontextmenu', false, true);        // Be ready to handle it    this.addEventListener('mycontextmenu', function (e) {      myContext.style.top = clickCoords.y      myContext.style.left = clickCoords.x      myContext.style.display= "block"    }, false);        // Dispatch it    this.dispatchEvent(event);  })})// Listener for the options of that "simulated context menu"contextItems.forEach(function(ci){  ci.addEventListener("click", function(e){    if(this.getAttribute("data-destination") === "tab"){      window.open(contextHref,"_blank")    }else{      window.open(contextHref,"custom",`width=${0.99*screen.width},height=${0.94*screen.height}`)    }  })})// To hide the "simulated context menu" when there is a click anywhere else than on a .context-anchor elementdocument.addEventListener("click", function(e){  if(myContext.style.display==="block" && e.target.classList.toString().split(" ").indexOf("context-anchor")<0){    myContext.style.display= "none"  }}).context{  display: none;  position: absolute;  top: 0;  left: 0;  border: 1px solid lightgrey;  background: white;  margin: 1em;  box-shadow: 2px 2px 2px grey;  min-width: 15em;}.context-item{  font-family: "arial";  padding: 0.5em 2em;}.context-item:hover{  background: lightgrey;}<a href="https://stackoverflow.com" class="context-anchor"> Anchor </a><br><br><a href="http://hmpg.net/" > Normal anchor </a><!-- The simulated context menu --><div class="context">  <div class="context-item" data-destination="tab">Open link in a new tab</div>  <div class="context-item" data-destination="window">Open link in a new window</div></div>注意:window.open由于明显的原因在 SO 片段中被阻止。这绝对是很多代码来创建一个奇怪和不常见的浏览器行为。所以我不会推荐任何人使用它。

大话西游666

如果您想在菜单中打开“在新标签页中打开”和“在新窗口中打开”选项,为什么只使用 HTML?<html>&nbsp; <head></head>&nbsp; <body>&nbsp; &nbsp; <a href="https://stackoverflow.com" id="anchor-el" target="_blank" title="If you run this snippet and click on this link, it won't work because you need to run it in your own editor"> Anchor </a>&nbsp; </body></html>每当单击时,上面的代码将在新选项卡中打开。右键单击时,还会有一个在新选项卡中打开和在新窗口中打开的选项。“target”属性指定链接将在何处打开;下面是一些例子:target="_blank" - "Opens in new tab"target="_self" - "Opens in the same tab"target="_parent" - "Opens in the parent frame"target="_top" - "Opens in the full body of the window"

哔哔one

如果我理解正确的话,你必须创建一个自定义的contextmenu. 所以这是一个例子。const menu = document.querySelector('[data-id=anchor-el]')const anchor = document.getElementById('anchor-el');anchor.addEventListener('contextmenu', e => {&nbsp; e.preventDefault();&nbsp; menu.style.top = e.pageX;&nbsp; menu.style.top = e.pageY;&nbsp; menu.style.display = 'block';});menu.querySelector('li#newTab').addEventListener('click', (evt) => {&nbsp; evt.preventDefault();&nbsp; console.log('clicked open in new tab');&nbsp; window.open(anchor.href);});menu.querySelector('li#newWin').addEventListener('click', (evt) => {&nbsp; evt.preventDefault();&nbsp; console.log('clicked open in new window');&nbsp; window.open(anchor.href, '_blank', 'toolbar=0,location=0,menubar=0');});document.body.addEventListener('click', (evt) => {&nbsp; evt.preventDefault();&nbsp; evt.stopPropagation();&nbsp; menu.style.display = 'none';});[data-id="anchor-el"] {&nbsp; width: 15rem;&nbsp; display: flex;&nbsp; margin: 0;&nbsp; padding: 0;&nbsp; align-items: stretch;&nbsp; align-content: space-evenly;&nbsp; flex-direction: column;&nbsp; justify-content: space-evenly;&nbsp; box-shadow: 0 0.25rem 0.325rem 0.175rem rgba(0, 0, 0, 0.2);&nbsp; position: relative;&nbsp; display: none;}[data-id="anchor-el"] ul li {&nbsp; width: 100%;&nbsp; list-style: none;&nbsp; margin: 0;&nbsp; padding: 0.5rem;&nbsp; position: relative;&nbsp; color: #000;&nbsp; font-weight: 500;&nbsp; font-size: 1rem;&nbsp; cursor: pointer;}[data-id="anchor-el"] ul li:hover {&nbsp; color: #f00;}<a href="https://stackoverflow.com" id="anchor-el"> Anchor </a><div>&nbsp; <div type="context" data-id="anchor-el">&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; <li label="Open in new tab" id="newTab">Open in new tab</li>&nbsp; &nbsp; &nbsp; <li label="Open in new window" id="newWin">Open in new window</li>&nbsp; &nbsp; </ul>&nbsp; </div></div>

繁星淼淼

document.getElementById("anchor-el").addEventListener("click", function() {&nbsp; &nbsp; var link = document.getElementById('anchor-el').getAttribute("href");&nbsp; &nbsp; window.open(link,'_blank');});

白衣染霜花

打开本机系统上下文菜单,例如默认的右键单击上下文菜单是不可能的。您当然可以使用 jQuery 创建自己的上下文菜单,例如:https://swisnl.github.io/jQuery-contextMenu/作为如何使用库的示例:&nbsp;$(function() {&nbsp; &nbsp; &nbsp; &nbsp; $.contextMenu({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selector: '#example',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; trigger: 'left',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback: function(key, options) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var m = "clicked: " + key;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.console && console.log(m) || alert(m);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; items: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "edit": {name: "Edit", icon: "edit"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "cut": {name: "Cut", icon: "cut"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;copy: {name: "Copy", icon: "copy"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "paste": {name: "Paste", icon: "paste"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "delete": {name: "Delete", icon: "delete"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "sep1": "---------",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "quit": {name: "Quit", icon: function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 'context-menu-icon context-menu-icon-quit';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; /* prevent the default switching to the target site */&nbsp; &nbsp; &nbsp; &nbsp; $("#example").on("click", function(event) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.7.1/jquery.contextMenu.min.css" rel="stylesheet"/><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.7.1/jquery.contextMenu.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.7.1/jquery.ui.position.js"></script><a href="https://google.com" id="example">click me</a>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript