javascript事件对象之事件切换器
html代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jstest</title> <link rel="stylesheet" type="text/css" href="style.css"/> <script type="text/javascript" src="js.js"></script> </head> <body> <div id="box" class="red">测试div</div> </body> </html>
css代码
@charset "utf-8"; .red{width:100px; height:100px; background:#f00;} .blue{width:100px; height:100px; background: blue;}
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(obj,fn,false); }else if(obj.detachEvent){ obj.detach('on'+type,fn); } } //跨浏览器获取目标对象 function getTarget(evt){ if(evt.target){ //w3c return evt.target; }else if(window.event.srcElement){ return window.event.srcElement; } } addEvent(window,'load',function(){ var box = document.getElementById('box'); addEvent(box,'click',toBlue); }); function toRed(evt){ var that = getTarget(evt); that.className = 'red'; removeEvent(that,'click',toRed); addEvent(that,'click',toBlue); } function toBlue(evt){ var that = getTarget(evt); that.className = 'blue'; removeEvent(that,'click',toBlue); addEvent(that,'click',toRed); }