首页 > 代码库 > 一些web事件兼容(根据高级程序)
一些web事件兼容(根据高级程序)
var EventUtil = {
//事件监听
addHandler: 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;
}
},
//移除事件
removeHandler: function( element, type, handler ) {
if ( element.removeEevntListener ) {
element.removeEevntListener(type, handler, false);
} else if ( element.detachEvent ) {
element.detachEvent("on" + type, handler);
} else {
element["on" + type] = null;
}
},
//事件对象
getEvent: function( event ) {
return event ? event : window.event;
},
//事件目标
getTarget: function( event ) {
return event.target || window.srcElement;
},
//阻止默认事件
preventDefault: function( event ) {
if ( event.preventDefault ) {
event.preventDefault();
} else {
event.returnValue = http://www.mamicode.com/false;
}
},
//阻止事件冒泡
stopPropagation: function( event ) {
if ( event.stopPropagation ) {
event.stopPropagation();
} else {
//cancelBubble的默认值是false
event.cancelBubble = true;
}
},
//鼠标跨浏览器兼容事件
getRelatedTarget: function( event ) {
//IE8<=不支持relatedTarget,relatedTarget事件属性返回与事件的目标节点相关的节点 支持toElement和formElement
if ( event.relatedTarget ) {
return event.relatedTarget;
} else if ( event.toElement ) {
return event.toElement;
} else if ( event.formelement ) {
return event.formelement;
} else {
return null;
}
},
//鼠标按钮Button的兼容
//implementation.hasFeature检测DOM版本
getButton: function( event ) {
if ( document.implementation.hasFeature("MouseEvents","2.0") ) {
return event.button;
} else {
switch( event.button ) {
case 0:
case 1:
case 3:
case 5:
case 7:
//按下左侧按钮
return 0;
case 2:
case 6:
//按下右侧按钮
return 2;
case 4:
return 1;
//按下中间按钮
}
}
},
//鼠标滚轮事件兼容
getWheelDelta: function( event ) {
if ( event.wheelDelta ) {
return (client.engine.opera && client.engine.opera < 9.5 ? -event.wheelDelta : event.wheelDelta);
} else {
//由于火狐的值不一样所以,这个值首先反向,然后再乘以40;
return -event.detail * 40;
}
},
//keyCode和keypress兼容
getCharCode: function( event ) {
if ( typeof event.charCode == "number" ) {
return event.charCode;
} else {
return event.keyCode;
}
},
};
能力有限,有幸能够得到您的访问,万分感谢
一些web事件兼容(根据高级程序)