简体   繁体   English

禁用特定容器及其子项的上下文菜单

[英]Disable contextmenu for a specific container and its children

I need to disable contextmenu only inside a specific div #wrapper and its children, and not the whole page.我需要禁用contextmenu里面只有一个特定的div #wrapper其子女,而不是整个页面。 This is what I'm doing:这就是我正在做的:

document.addEventListener('contextmenu', function (event) {
    console.log(event.target.id);
    if (event.target.id === 'wrapper') {
        event.preventDefault();
    }
});

.. but it doesn't seem to work. ..但它似乎不起作用。

You're approaching this the wrong way: you're adding the listener to the document , which may be ok, but it's easier to add it to the element itself, and you are checking event.target.id , which is the ID of the current clicked element (eg a children of your wrapper), not the wrapper.您以错误的方式处理此问题:您将侦听器添加到document ,这可能没问题,但将其添加到元素本身更容易,并且您正在检查event.target.id ,它是当前单击的元素(例如包装器的子元素),而不是包装器。

To make this work you can easily do something like this instead:要完成这项工作,您可以轻松地执行以下操作:

var myWrapper = document.getElementById('wrapper');

myWrapper.addEventListener('contextmenu', function(e) {
    e.preventDefault();
}, true);

The code you have in your question works perfectly.您在问题中的代码完美无缺。 One possibility of why the context menu still showed up is that you in fact clicked on a child of #wrapper , instead of clicking on the element itself:上下文菜单仍然显示的一种可能性是您实际上单击了#wrapper的子#wrapper ,而不是单击元素本身:

HTML HTML

<div id="wrapper">
    #wrapper

    <div class="inner">
        #wrapper .inner
    </div>
</div>

Working example demonstrating this issue on JSFiddle.在 JSFiddle 上演示此问题的工作示例。

You can overcome this by attaching the event handler to the desired element directly instead.您可以通过将事件处理程序直接附加到所需元素来解决这个问题。 This way, right-click events on child-elements will bubble up to #wrapper , and thus fire the event as expected:这样,子元素上的右键单击事件将冒泡到#wrapper ,从而按预期触发事件:

JavaScript JavaScript

document.getElementById('wrapper').addEventListener('contextmenu', function (event) {
    event.preventDefault();
});

Working example on JSfiddle. JSfiddle 上的工作示例。

This is a solution that work fine这是一个工作正常的解决方案

<div id="wrapper" oncontextmenu="return false">
#wrapper

<div class="childds">
    
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM