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,fa);
    }
}

//跨浏览器移除事件
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);
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。