【问题标题】:Javascript toggle default and custom contextmenu on right-clickJavascript 在右键单击时切换默认和自定义上下文菜单
【发布时间】:2020-07-31 17:13:34
【问题描述】:

我想在用户右键单击页面上的某些元素(即表格)时显示自定义上下文菜单。 到目前为止,我有自定义和默认上下文菜单显示。

function element_right_clicked(sender,e){
if(e.which == 3){
      // code here that displays custom menu
      sender.addEventListener("contextmenu", e => {
        e.preventDefault();
    });
  }
}

我正在寻找一种方法,在显示自定义时不显示默认菜单。

【问题讨论】:

  • 您所包含的代码是否存在特定问题?
  • 你能澄清一下吗?你想要两者的结合?
  • 在什么情况下应该显示正常上下文菜单,或者你的自定义菜单?
  • 如果您可以在运行时显示此问题,请创建一个小提琴或沙箱。
  • 为什么不只将事件监听器应用于那些元素,而不是window

标签: javascript contextmenu right-click


【解决方案1】:

只需将处理程序设置为仅处理需要显示自定义菜单的元素。您可以通过将一个类应用于任何应该使用自定义菜单的元素,然后在文档级别侦听右键单击并利用event delegation,轻松做到这一点。

下面的红色项目配置为自定义右键单击。

let modal = document.getElementById("contextMenu");

// Set up an event handler for the documnt right click
document.addEventListener("contextmenu", function(event) {
  // Only do something when the element that was actually right-clicked
  // on has the right class to trigger the menu
  if(event.target.classList.contains("customMenu")){
    event.preventDefault();
    modal.classList.remove("hidden");
  }
});

// Close the menu when you left click anywhere
document.addEventListener("click", function(event){
  modal.classList.add("hidden");
});
.hidden {display:none;}
.customMenu { font-weight:bold; color:#f00; }
#contextMenu {
  position:absolute; 
  border:2px double #333; 
  width:150px; 
  height:175px;
  top:20%;
  left:30%;
  background-color:#e0e0e0;
  box-shadow:5px 5px #909090;
}
<div class="customMenu">1</div>
<div id="one">2</div>
<div class="customMenu">3</div>
<div>4</div>
<div>5
  <span class="customMenu">6</span>
</div>
<div>6
  <h1>7
    <div class="customMenu">8</div>
  </h1>
</div>
<div class="customMenu">9</div>

<div id="contextMenu" class="hidden">
  <ul>
    <li>menu item</li>
    <li>menu item</li>
    <li>menu item</li>
    <li>menu item</li>
    <li>menu item</li>
    <li>menu item</li>
  </ul>
</div>

【讨论】:

    【解决方案2】:

    您好,您可以从事件的 traget 属性中检测到。

    window.oncontextmenu = (e) => {
      if (e.target.id === "customdiv") {
    
        e.preventDefault();
       //Show custom context menu here
      }
    
    }
    

    https://jsfiddle.net/asutosh/o87qmbx6/7/

    【讨论】:

    • 但这不会恢复默认行为
    • 当你想调用/恢复默认操作时,请检查:stackoverflow.com/questions/7732854/…
    • 这看起来正是我想要的。谢谢
    • @goryef 很好,您已经找到了解决方案。
    猜你喜欢
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多