addEventListener

element.addEventListener(event, function, useCapture)

event:指定事件名

function:指定事件触发时执行的函数。

useCapture:布尔值,指定事件在捕获或冒泡阶段执行。true:事件在捕获阶段执行,false:事件在冒泡阶段执行。

例子:

html代码:

   <div id="parent"> 
        <div id="child">
        </div>
    </div>

css代码:

  #parent{
        width: 400px;
        height: 120px;
        background-color: green;
        margin: 50px;
    }
    #child{
        width: 100px;
        height: 120px;
        background-color: orange;
        margin-left: 80px;
        cursor: pointer;
    }

效果图:

js代码:

     var child = document.getElementById('child');
        var parent = document.getElementById('parent');

        parent.addEventListener('click',function(){
            console.log(1);
        },true);
        parent.addEventListener('click',function(){
            console.log(2);
        },false);
        child.addEventListener('click',function(){
            console.log(3);
        },true);
        child.addEventListener('click',function(){
            console.log(4);
        },true);

点击child元素后,打印结果为:1 3 4 2

分析:点击事件后,事件从元素向目标元素传递(捕获阶段),然后到目标元素(目标阶段),最后从目标元素向根元素传递。在捕获阶段中,输出1,在目标阶段输出3,4,在冒泡阶段输出2。

posted @ 2016-08-01 22:49  springmin  阅读(214)  评论(0编辑  收藏  举报