首页 > 编程语言 > 详细

javascript事件对象之事件切换器

时间:2014-09-17 00:58:01      阅读:308      评论:0      收藏:0      [点我收藏+]

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

 

javascript事件对象之事件切换器

原文:http://www.cnblogs.com/littlefly/p/3976106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!