基本原理是偵測document的點擊事件,在事件參數ev中有個事件目標ev.target,顯示了點擊事件的目標元件。從這個事件目標開始往父元件搜尋,若沒比對到註冊事件的元件的話,就觸發監聽器。
暫且把這個事件稱作外點擊事件Outclick。
===
===
document.onOutclickedListeners = [];
document.addEventListener("click", function (ev) {
var listeners = $.extend(true, [], document.onOutclickedListeners);
var target = ev.target;
do {
for (var l = 0; l < listeners.length; ++l) {
var listener = listeners[l];
if (listener.element === target) {
listeners.splice(l, 1);
}
}
target = target.parentNode;
} while (target);
for (var listener of listeners) {
listener.func(ev);
}
});
document.addEventListener("click", function (ev) {
var listeners = $.extend(true, [], document.onOutclickedListeners);
var target = ev.target;
do {
for (var l = 0; l < listeners.length; ++l) {
var listener = listeners[l];
if (listener.element === target) {
listeners.splice(l, 1);
}
}
target = target.parentNode;
} while (target);
for (var listener of listeners) {
listener.func(ev);
}
});
===.