自己封装的跨浏览器事件对象,分享给大家,源码如下,并且有注释。
//跨浏览器的事件对象
var EventUtil = { //注册事件 addHandler : function (element, type ,handler) { if (element.addEventListener) { element.addEventListener(element, type, handler, false); } else if (element.attachEvent) { element.attachEvent(element, "on" + type, handler); } else { element["on" + element] = handler; } }, //获取事件对象 getEvent : function (event) { return event ? event : window.event; }, //获取事件发生的目标元素 getTarget : function (event) { return event.target || event.srcElement; }, //获取事件发生的相关元素(这个事件,知识针对mouseover和mouseout,其他事件这个属性为null getRelatedTarget : function (event) { if (event.getRelatedTarget) { return event.getRelatedTarget; //ie8及以前,不支持getRelatedTarget,但是mouseout,toElement这个属性保存相关元素 //mouseover,fromElement这个属性保存相关元素 } else if (event.toElement) { return event.toElement; } else if (event.formElement) { return event.formElement; } else { return null; } } //获取鼠标事件 getButton : function () { if (document.implementation.hasFeature("MouseEvents", "2.0") { return event.getButton; //ie8及以前 } else { switch(event.button) { case 0: do something//表示没有按下按钮 case 1: do something//按下主鼠标按钮 case 2: do something//按下次鼠标按钮 case 3: do something//同时按下,主次鼠标按钮 case 4: do something//按下中间按钮 case 5: do something//按下主,中间按钮 case 6: do something//按下次,中间按钮 case 7: do something//同时按下三个按钮 } } }, //鼠标滚轮 getWheelDelta : function (event) { if (event.wheelDelta) { return (client.engine.opera && client.engine.opera < 9.5 ? -event.wheelDelta : event.wheelDelta); } else { return -event.detail*40; } }, //获取keypress按键code getCharCode : function (event) { if (typeof event.charCode == "number") { return event.charCode; } else { return event.keyCode; } } //取消事件的默认行为 preventDefault : function (event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, //移出事件 removeHandler : function (element, type ,handler) { if (element.removeEventListener) { element.removeEventListener(element, type, handler, false); } else if (element.attachEvent) { element.detachEvent(element, "on" + type, handler); } else { element["on" + element] = null; } }, //取消事件冒泡 stopPropagation : function (event) { if (event.stopPropagation) { event.stopPropagation; } else { event.cancelBubble = false; } } };
目前,没有发现bug,后期持续维护更新,谢谢。