js事件事件理解

 

js事件事件理解

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>js事件流模型</title>
</head>

<style>
    #con{
        width:200px;
        height:200px;
        background: orange;
    }
    #outer{
        position: relative;
        top: 50px;
        left: 50px;
        width:100px;
        height:100px;
        background: #eeddff;
    }
    #inner{
        position: relative;
        top: 251px;
        left: 25px;
        width:50px;
        height:50px;
        background: #44ddff;
    }
</style>
<body>
<div id="con">
con
    <div id="outer">
    outer
        <div id="inner">inner</div>
    </div>
</div>

<script>
 </script>

</body>
</html>

 

1.执行顺序

document->html->body-con->outer->ineer->outer->con->body->html->document

2.响应某个时间的函数叫做事件处理程序

function fnHandler(){
}
<script>
    // js事件流
    // 事件添加
    var con = document.getElementById('con');
    // con.addEventListener('click',function(){
    //     alert('123');
    // });

    // con.addEventListener('click',function(){
    //     alert('123');
    // },false);

    // con.addEventListener('click',function(){
    //     alert('123');
    // },true);
    

// DOM事件流
// DOM2级事件规定事件流包括三个阶段:事件捕获阶段、处于目标阶段和事件冒泡阶段。
// DOM2级事件定义了两个方法addEventListener()和removeEventListener()
// IE不同的它有自己的方法attachEvent()和detachEvent

var  eventUtils = {
    // addEventHandler:function(){}
    addEventHandler: function(el,event,fnHandler){
        // console.log('test');
        if(el.addEventListener){
            console.log(el.addEventListener);
            el.addEventListener(event,fnHandler,true)
        }
            else{
                console.log(el.attachEvent);
                el.attachEvent('on'+event,fnHandler)}
    },
    removeEventHandler: function(el,event,fnHandler){
        // console.log('test');
        if(el.removeEventListener){
            console.log(el.removeEventListener);
            el.removeEventListener(event,fnHandler,true)
        }
            else{
                console.log(el.detachEvent);
                el.detachEvent('on'+event,fnHandler)}
    }
}

eventUtils.addEventHandler(con,'click',function(){
            alert('123');
    });
</script>

 

posted @ 2017-09-05 20:06  alan-alan  阅读(246)  评论(0编辑  收藏  举报