常见写法
1 let addEvent = (ele, type, handler) => {
2 if (window.addEventListener) {
3 return ele.addEventListener(type, handler, false);
4 }
5 if (window.attachEvent) {
6 return ele.attachEvent(`on${type}`, handler);
7 }
8 };
嗅探
1 let addEvent = (() => {
2 if (window.addEventListener) {
3 return function (ele, type, handler) {
4 ele.addEventListener(type, handler, false);
5 };
6 }
7 if (window.attachEvent) {
8 return function (ele, type, handler) {
9 ele.attachEvent(`on${type}`, handler);
10 };
11 }
12 })();
惰性载入
1 let addEvent = (ele, type, handler) => {
2 if (window.addEventListener) {
3 addEvent = function (ele, type, handler) {
4 ele.addEventListener(type, handler, false);
5 };
6 }
7 if (window.attachEvent) {
8 addEvent = function (ele, type, handler) {
9 ele.attachEvent(`on${type}`, handler);
10 };
11 }
12 addEvent(ele, type, handler);
13 };