2 回答

TA贡献1828条经验 获得超3个赞
function eventDelegate (e,targetSelector,fn) {
// 兼容性处
let event = e || window.event;
// 获取到目标阶段指向的元素
let target = event.target || event.srcElement;
// 获取到代理事件的函数
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;
// 执行绑定的函数,注意 this
fn.call(sTarget, Array.prototype.slice.call(arguments))
}
target = target.parentNode;
}
添加回答
举报