处理元素外部的点击而不使用jquery

Dan*_*Dan 3 javascript jquery event-handling

我想实现这样的解决方案

如何检测元素外部的单击?

但我正在使用另一个已定义$()函数的javascript库

有什么建议?

use*_*716 6

这很容易实现.为一个功能加载jQuery库会很遗憾.

如果您正在使用的其他库处理事件绑定,您可以在该库中执行相同的操作.由于您没有指出其他库是什么,这是一个原生解决方案:

示例: http ://jsfiddle.net/patrick_dw/wWkJR/1/

window.onload = function() {

    // For clicks inside the element
    document.getElementById('myElement').onclick = function(e) {
            // Make sure the event doesn't bubble from your element
        if (e) { e.stopPropagation(); } 
        else { window.event.cancelBubble = true; }
            // Place the code for this element here
        alert('this was a click inside');
    };

    // For clicks elsewhere on the page
    document.onclick = function() {
        alert('this was a click outside');
    };
};
Run Code Online (Sandbox Code Playgroud)