页面中间点击监听器

Page Middle Click Listener

我需要在使用中键时弹出警告,如果我在 link 上单击它,但在页面的任何其他元素上(或只是在空白 space).

var test = {
pageMiddleClickListener : function(e) {
    if(e.which === 2) {     
        //if (!gContextMenu.onLink) {
            alert('ok');
        //}
    }
}
window.addEventListener("click",test.pageMiddleClickListener,false);

当我在 link 上使用中键时出现警报,但我需要阻止此行为 links

我需要像“!gContextMenu.onLink”这样的东西,但不是上下文菜单(没有)

您可以使用 prop 方法检查您是否点击了 <a>

$(this).prop("tagName") == "A"

在您的事件侦听器中:

var test = {
   pageMiddleClickListener : function(e) {
       if(e.which === 2) {     

        // not an <a> ?
        if ($(this).prop("tagName") !== "A") {
            alert('ok');
        }
   }
}
window.addEventListener("click",test.pageMiddleClickListener,false);

您可以通过多种方式测试点击的 target 是否为 link。一种方法是检查 Element.tagName 是否为 A,另一种方法是测试 href 属性。事实证明,也有必要测试目标的 parentNodes 是否是 links.

var test = {
    pageMiddleClickListener : function(e) {
        if(e.button === 1) {     
            if (!test.isLinkOrAParentIsLink(e.target)) {
                e.view.alert('ok');
            }
        }
    },

    isLinkOrAParentIsLink : function(el) {
        if (el.tagName === "A") {
            return true;
        } //else
        let parent= el.parentNode;
        while (parent !== null && typeof parent.tagName !== "undefined") {
            if (parent.tagName === "A") {
                return true;
            } //else
            parent= parent.parentNode;
        }
        return false;
    }
}
window.addEventListener("click",test.pageMiddleClickListener,false);

    isLinkOrAParentIsLink : function(el) {
        if (el.hasAttribute("href")) {
            return true;
        } //else
        let parent= el.parentNode;
        while (parent !== null && typeof parent.tagName !== "undefined") {
            if (parent.hasAttribute("href")) {
                return true;
            } //else
            parent= parent.parentNode;
        }
        return false;
    }

注:我改的e.which to e.button as that is what is in the specification for click events and MouseEvent.which是非标准的。请注意,这还需要测试 e.button === 1 而不是 2.