javascript处理事件的一些兼容写法
2010-09-14 13:47:24 来源:WEB开发网绑定事件var addEvent = function( obj, type, fn ) {
另一个实现
if (obj.addEventListener)
obj.addEventListener( type, fn, false );
else if (obj.attachEvent) {
obj["e"+type+fn] = fn;
obj.attachEvent( "on"+type, function() {
obj["e"+type+fn]();
} );
}
}; var addEvent = (function () {
移除事件
if (document.addEventListener) {
return function (el, type, fn) {
el.addEventListener(type, fn, false);
};
} else {
return function (el, type, fn) {
el.attachEvent('on' + type, function () {
return fn.call(el, window.event);
});
}
}
})(); var removeEvent = function(obj, type, fn) {
加载事件与脚本
if (obj.removeEventListener)
obj.removeEventListener( type, fn, false );
else if (obj.detachEvent) {
obj.detachEvent( "on"+type, obj["e"+type+fn] );
obj["e"+type+fn] = null;
}
} var loadEvent = function(func) {
阻止事件
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}else {
window.onload = function() {
oldonload();
func();
}
}
} var cancelEvent = function(event) {
取得事件源对象
event = event||window.event
if (event.preventDefault) {
event.preventDefault( );
event.stopPropagation( );
} else {
event.returnValue = false;
event.cancelBubble = true;
}
}
相当于Prototype.js框架的Event.element(e)
var getTarget = function(event){
event = event || window.event;
var obj = event.srcElement ? event.srcElement : event.target;
return obj
}
Tags:javascript 处理 事件
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接