Handling clicks outside an element without jquery

南楼画角 提交于 2020-07-09 05:00:23

问题


I would like to implement the solution like this

How do I detect a click outside an element?

but I'm using another javascript library with $() function already defined

Any suggestions?


回答1:


This is easy to accomplish. Would be a shame to load the jQuery library just for one feature.

If the other library you're using handles event binding, you could do the same thing in that library. Since you didn't indicate what that other library is, here's a native solution:

Example: 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');
    };
};



回答2:


If the $ conflict is your only hold-up, there are ways around that: http://docs.jquery.com/Using_jQuery_with_Other_Libraries




回答3:


I also add here the code that stops event bubbling up. Found on quircksmode.org

 function doSomething(e) {
    if (!e) var e = window.event
    // handle event
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
 } 


来源:https://stackoverflow.com/questions/4320553/handling-clicks-outside-an-element-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!