JS——事件冒泡与捕获

事件冒泡与事件捕获

1、冒泡:addEventListener("click",fn,false)或者addEventListener("click",fn);捕获:addEventListener("click",fn,true)。

2、区别:冒泡是从触发该事件的目标节点一层一层往上将同种类型的事件触发;捕获是从触发该事件的目标节点最高一级的父节点开始将同种类型事件往下一层一层触发直到事件的目标的节点。

结合上图可以看出,ele1与ele2都通过addEventListener注册了点击事件的话

(1)如果参数是true的话,在点击了ele2的时候,会首先进入捕获阶段,因为参数是true,捕获阶段会触发,那么首先会响应的是ele1的点击事件,随后是ele2,因为是false所以不会触发冒泡阶段

(2)如果参数是false的话,在点击了ele2的时候,虽然会首先进入捕获阶段,但是不会有任何响应,在进入随后的冒泡阶段则会首先响应ele2的点击事件,随后才是ele1

冒泡的顺序

IE6:div=》body=》html=》document

其他:div=》body=》html=》document=》window

不支持冒泡的事件:

blur、focus、load、unload、onmouseenter、onmouseleave

target与bubbles

target:触发此事件的目标

bubbles:此事件是否支持冒泡

target兼容问题:

//IE678支持event.srcElement(事件源)
//火狐谷歌IE9以上支持event.target(事件源)
//兼容写法获取元素ID:
var event = event || window.event;
var targetId =  event.target ?  event.target.id : event.srcElement.id;

点击最小的div,冒泡和捕获返回结果不同

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box1 {
            width: 400px;
            height: 400px;
            background-color: red;
        }

        .box2 {
            width: 200px;
            height: 200px;
            background-color: yellow;
        }

        .box3 {
            width: 100px;
            height: 100px;
            background-color: green;
        }
    </style>
</head>
<body>
<div class="box1">
    <div class="box2">
        <div class="box3"></div>
    </div>
</div>
<script>
    var box1 = document.getElementsByTagName("div")[0];
    var box2 = box1.children[0];
    var box3 = box2.children[0];
    box1.addEventListener("click", function () {
        console.log("box1");
    }, false);
    box2.addEventListener("click", function () {
        console.log("box2");
    }, false);
    box3.addEventListener("click", function () {
        console.log("box3");
    }, false);
</script>
</body>
</html>
最后结果:
box3
box2
box1
<script>
    var box1 = document.getElementsByTagName("div")[0];
    var box2 = box1.children[0];
    var box3 = box2.children[0];
    box1.addEventListener("click", function () {
        console.log("box1");
    }, true);
    box2.addEventListener("click", function () {
        console.log("box2");
    }, true);
    box3.addEventListener("click", function () {
        console.log("box3");
    }, true);
</script>
最后结果:
box1
box2
box3

 阻止冒泡

//火狐谷歌IE11支持event.stopPropagation
//IE10以下则是使用event.cancelBubble = true
<script>
    box.onclick = function (event) {
        var event = event || window.event;
        console.log(event.target);
        if (event && event.stopPropagation) {
            event.stopPropagation();
        } else {
            event.cancelBubble = true;
        }
    }
</script>
posted @ 2017-12-05 15:16  var_obj  阅读(382)  评论(0编辑  收藏  举报