1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
// 每次绑定事件都要判断一次
function addEvent(type, el, fn, capture = false) {
if (window.addEventListener) {
el.addEventListener(type, fn, capture);
} else if (window.attachEvent) {
el.attachEvent('on' + type, fn);
}
}
// 仅在初次调用时判断
const addEvent = (function () {
if (window.addEventListener) {
return function (type, el, fn, capture) {
el.addEventListener(type, fn, capture);
};
} else if (window.attachEvent) {
return function (type, el, fn) {
el.attachEvent('on' + type, fn);
};
}
})();
// 惰性函数来实现
function addEvent(type, el, fn, capture = false) {
// 重写函数
if (window.addEventListener) {
addEvent = function (type, el, fn, capture) {
el.addEventListener(type, fn, capture);
};
} else if (window.attachEvent) {
addEvent = function (type, el, fn) {
el.attachEvent('on' + type, fn);
};
}
// 执行函数
addEvent(type, el, fn, capture);
}
|