绑定事件
addEventListener:W3C标准写法IE不兼容
attachEvent:兼容IE
注意:1:事件名不同:IE下要加“on“,W3C不加
2:加载事件的执行顺序不同,W3C按绑定事件的顺序来执行,而IE6,7是后绑定的时间先发生
3:this的指向,W3C中,绑定函数中的this指向DOM对象,而IE6,7指向WINDOWS对象
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
}