简体   繁体   English

jQuery上除“输入”以外的所有内容上的自定义上下文菜单

[英]Custom Context Menu on everything except “input” in jQuery

I want to add custom context menu with jQuery for the whole body of the page, except the textfields. 我想为整个页面的主体添加带有jQuery的自定义上下文菜单,文本框除外。 How can I do that? 我怎样才能做到这一点? I have tried that code: 我已经尝试过该代码:

$('body:not(input)').bind('contextmenu', function(){
    /*code*/
});

Check the srcElement before plugin executions. 插件执行前检查srcElement If it's not an input element, do trigger the contextmenu plugin: 如果不是输入元素,请触发contextmenu插件:

$(document).on("contextmenu", function(e) {
    if (!$(e.srcElement).is(":input")) { // if it's not an input element...
        $(this).triggerTheContextMenuPlugin();
    }
});

Use an event listener on the document and check if it was initiated by an input element. document上使用事件侦听器,并检查它是否由输入元素启动。

$(document).on("contextmenu", function (e) {
    if (e.target.tagName.toUpperCase() === "INPUT") {
        console.log("context menu triggered");
    }
});

Demo here 在这里演示

Inspired by Salman's solution. 受Salman解决方案的启发。

You can stop the event propagation in all input elements, with the e.stopPropagation() function. 您可以使用e.stopPropagation()函数停止所有输入元素中的事件传播 In doing so, you keep the default behavior of the inputs elements: 这样,您可以保留inputs元素的默认行为:

$(function() {
    $(document).on("contextmenu", function(e) {
        alert("Context menu triggered, preventing default");
        e.preventDefault();
    });
    $("input").on("contextmenu", function(e) {
        e.stopPropagation();
    });
});

JSFiddle Demo JSFiddle演示

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

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