当用户右键单击页面上的某些元素(即表格)时,我想显示一个自定义的conext菜单。截至目前,我同时具有自定义和默认上下文菜单显示。
function element_right_clicked(sender,e){
if(e.which == 3){
// code here that displays custom menu
sender.addEventListener("contextmenu", e => {
e.preventDefault();
});
}
}
我正在寻找一种方法,在显示自定义项时不显示默认菜单。
只需将处理程序设置为仅对需要显示自定义菜单的那些元素进行处理即可。通过将类应用于应该使用自定义菜单的任何元素,然后在文档级别侦听右键单击并利用事件委托,可以轻松地实现此目的。
下面的红色项目已配置为自定义右键单击。
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句