所有 "a elements" 上的自定义右键单击菜单

Custom right click menu on all "a elements"

我有这个 JavaScript,使用时将仅在第一个 a 元素上打开我的自定义右键单击菜单。我如何让它在每个 a 元素上打开?

const ctxmenu = document.querySelector('.ctxmenu') //target element
const baseEL = document.querySelector('a') //base element

document.addEventListener('contextmenu', e => {
  ctxmenu.classList.remove('show')
})
document.addEventListener('click', e => {
  ctxmenu.classList.remove('show')
})

baseEL.addEventListener('contextmenu', e => {
  e.preventDefault()
  e.stopPropagation() //important!!

  //move element
  ctxmenu.style.top = e.y + 'px'
  ctxmenu.style.left = e.x + 'px'

  //show element
  ctxmenu.classList.add('show')
})
.ctxmenu {
  display: none;
  position: absolute;
  z-index: 99999;
  background-color: white;
}

.ctxmenu.show {
  display: block;
}

.ctxmenu .list {
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
}

.ctxmenu .listitem {
  position: relative;
  display: block;
  border: 1px solid rgba(0, 0, 0, .125);
  padding: .75rem 1.25rem;
  cursor: pointer;
}

.ctxmenu .listitem:hover {
  background-color: rgba(233, 233, 233, .5);
}

.box {
  height: 300px;
  width: 300px;
  border: 1px solid rgba(0, 0, 0, .125);
}

body {
  background-color: black;
}

a {
  color: lightblue;
}
<div class="ctxmenu">
  <ul class="list">
    <li class="listitem" onclick="window.open(z)">Open in new tab</li>
  </ul>
</div>
<a href="https://www.google.com/" onmouseover="z = this">Google</a><br />
<a href="https://duckduckgo.com/" onmouseover="z = this">DuckDuckGo</a>

JS Fiddle

我检查了你的代码,你使用的是 querySelector('a'),它会给你第一个匹配的元素。

你可能会做的是:

const elems = document.querySelectorAll('a');
elems.forEach(child => child.addEventListener('contextmenu', e => {
    e.preventDefault()
    e.stopPropagation() //important!!

    //move element
    ctxmenu.style.top = e.y + 'px'
    ctxmenu.style.left = e.x + 'px'

    //show element
    ctxmenu.classList.add('show')
}));

现在您可以触发所有元素的 contextmenu 事件 :)

您可以使用 document.querySelectorAll, which returns a NodeList of all matched elements, instead of document.querySelector,它仅 returns DOM 中的第一个匹配元素。

document.querySelectorAll('a')
   .forEach(a=>a.addEventListener("contextmenu", onContextMenu, false));
function onContextMenu(e){
  e.preventDefault()
  e.stopPropagation() //important!!

  //move element
  ctxmenu.style.top = e.y + 'px'
  ctxmenu.style.left = e.x + 'px'

  //show element
  ctxmenu.classList.add('show')
}