Open Genzhen opened 3 years ago
`export const myEvent = { // 页面加载完成后 readEvent: function(fn: any){ if(fn === null || fn === undefined){ fn = document } let oldOnload: any = window.onload; if(typeof window.onload !== "function"){ window.onload = fn } else { window.onload = function(){ oldOnload() fn() } } }, // 页面元素事件绑定 addEvent: function(element:any,type:any,handle:Function){ if(element.addEventListener){ // w3c // 参数分别表示事件类型、需要执行的函数、是否捕捉 element.addEventListener(type,handle,false) } else if(element.attachEvent){ element.attachEvent("on"+type,function(){ handle.call(element) }) } else { element["on"+type] = handle } }, removeEvent: function(element:any,type:any,handle:Function){ if(element.removeEventListener){ element.removeEventListener(type,handle,false) } else if (element.detachEvent){ element.detachEvent("on"+type,handle) } else { element["on"+type] = null } }, stopPropagation: function(ev:any){ if(ev.stopPropagation){ ev.stopPropagation() } else { ev.cancelBubble = true } }, preventDefault: function(ev:any){ if(ev.preventDefault){ ev.preventDefault() } else { ev.returnValue = false } }, // 获取事件目标 getTarget: function(event:any){ return event.target || event.srcElement; }, // 获取event对象的引用,取到事件的所有信息 getEvent: function(e:any){ let ev = e || window.event; if(!ev){ let c = this.getEvent.caller while(c){ ev = c.arguments[0] if(ev && Event === ev.constructor){ break; } c = c.caller } } return ev }
}`
let eventUtils = {
addEventListener:(ele,type,handler)=>{
if(ele.addEventListener){
ele.addEventListener(type,handler)
} else if(ele.attachEvent){
ele.attachEvent("on"+type,handler)
} else {
ele['on'+type] = handler
}
},
removeEventListener:(ele,type,handler)=>{
if(ele.addEventListener){
ele.removeEventListener(type,handler)
} else if(ele.attachEvent){
ele.detachEvent("on"+type,handler)
} else {
ele['on'+type] = null
}
}
}
`const EventUtils = { // 分别使用dom0||dom2||IE方式 来绑定事件 // 添加事件 addEvent: function(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } },
// 移除事件 removeEvent: function(element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } },
// 获取事件目标 getTarget: function(event) { return event.target || event.srcElement; },
// 获取 event 对象的引用,取到事件的所有信息,确保随时能使用 event getEvent: function(event) { return event || window.event; },
// 阻止事件(主要是事件冒泡,因为 IE 不支持事件捕获) stopPropagation: function(event) { if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } },
// 取消事件的默认行为 preventDefault: function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } };`
扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。