事件处理程序和事件对象总结

时间:2022-05-07 22:41:39

和require.js没关系,只是最近看了拿来练练手~~

1.html(引用require.js模块)

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #div{
            background-color: yellow;
            width:200px;
            height:200px;
            opacity: 0.5; 

        }
        #a{
            display: block;
            background-color: green;
            width:100px;
            height:100px;
        }
    </style>
</head>
<body>
    <div id="div">
        <a id="a" href="http://site.baidu.com/"></a>
    </div>
<script type="text/javascript" src="require.js" data-main="main.js"></script>
</body>
</html>

2.main.js(程序入口文件)

require(['event'],function(Mod){
var div=document.getElementById('div');
var a=document.getElementById('a');
var Mod=new Mod.O();
Mod.addHandler(a,'click',hander1);
function hander1(e){
Mod.preventDefault(e);
Mod.stopPropagation(e);
alert('a');
}
Mod.addHandler(div,'click',hander2);
function hander2(e){

alert('div');
}
});

3.event.js(跨浏览器的事件处理程序和事件对象)

define(function(){
    function O(){
    }
    O.prototype={
// 添加句柄
addHandler:function(element,type,handler){
    if(element.addEventListener){
        element.addEventListener(type,handler,false);
    }else if(element.attachEvent){
        element.attachEvent('on'+type,handler);
    }else{
        element['on'+type]=handler;
    }
},
// 删除句柄
removeHandler:function(element,type,handler){
    if(element.removeEventListener){
        element.removeEventListener(type,handler,false);
    }else if(element.detachEvent){
        element.detachEvent('on'+type,handler);
    }else{
        element['on'+type]=null;
    }
},
getEvent:function(event){
    return event?event:window.event;
},
getType:function(event){
    return event.type;
},
getElement:function(event){
    return event.target || event.srcElement;
},
preventDefault:function(event){
    if(event.preventDefault){
        event.preventDefault();
    }else{
        event.returnValue=false;
    }
},
stopPropagation:function(event){
    if(event.stopPropagation){
        event.stopPropagation();
    }else{
        event.cancelBubble=true;
    }
}
};

return {O:O};
});