2 回答

TA貢獻(xiàn)1828條經(jīng)驗 獲得超3個贊
function eventDelegate (e,targetSelector,fn) {
// 兼容性處
let event = e || window.event;
// 獲取到目標(biāo)階段指向的元素
let target = event.target || event.srcElement;
// 獲取到代理事件的函數(shù)
let currentTarget = event.currentTarget;
// 處理 matches 的兼容性
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
let matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
// 遍歷外層并且匹配
while (target !== currentTarget) {
// 判斷是否匹配到我們所需要的元素上
if (target.matches(targetSelector)) {
let sTarget = target;
// 執(zhí)行綁定的函數(shù),注意 this
fn.call(sTarget, Array.prototype.slice.call(arguments))
}
target = target.parentNode;
}
添加回答
舉報