js 事件绑定
//跨浏览器兼容
//跨浏览器添加事件
function addEvent(obj,type,fn){
if(obj.addEventListener){
obj.addEventListener(type,fn,false);
}else if(obj.attachEvent){
obj.attachEvent('on'+type,fn);
}
}
//跨浏览器移除事件
function removeEvent(obj,type,fn){
if(obj.removeEventListener){
obj.removeEventListener(type,fn,false);
}else if(obj.detachEvent){
obj.detachEvent('on'+type,fn);
}
}
//跨浏览器获取目标对象
function getTarget(evt){
if(evt.target){
return evt.target;
}else if(window.event.srcElement){
return window.event.srcElement;
}
}
//跨浏览器阻止默认行为
function preDef(evt){
var e = evt||window.event;
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue=false;
}
}
//调用方式
addEvent(window,'load',function(){
var oDiv = document.getElementById('div');
addEvent(oDiv,'click',blue);
});
function red(evt){
var that=getTarget(evt);
that.className='red';
removeEvent(that,'click',red);
addEvent(that,'click',blue);
}
function blue(evt){
var that=getTarget(evt);
that.className='blue';
removeEvent(that,'click',blue);
addEvent(that,'click',red);
}