咸鱼前端—js 事件捕获/冒泡

咸鱼前端—js 事件捕获/冒泡

事件冒泡

事件冒泡:多个元素嵌套,有层次关系,这些元素注册了相同的事件。里面的元素的事件出发后,外面的元素的该事件也自动触发。
例如:

<!DOCTYPE html>
<html>
<head>
    <title>冒泡车测试</title>
    <style type="text/css">
        #bx1 {
            width: 400px;
            height: 400px;
            background-color: red;
        }

        #bx2 {
            width: 300px;
            height: 300px;
            background-color: blue;
        }

        #bx3 {
            width: 200px;
            height: 200px;
            background-color: yellow;
        }

    </style>
</head>
<div id="bx1">
    <div id="bx2">
        <div id="bx3"></div>
    </div>
</div>
<script>
    var xy$ = function (id) {
        return document.getElementById(id)
    }
    xy$("bx1").onclick = function () {
        console.log(this.id)
    }
    xy$("bx2").onclick = function () {
        console.log(this.id)
    }
    xy$("bx3").onclick = function () {
        console.log(this.id)
    }
</script>
</body>
</html>

点击bx3 ,bx1和bx2 都有效果
在这里插入图片描述

阻止事件冒泡

阻止事件冒泡方法

window.event.cancelBubble=true;//谷歌,IE8支持,火狐不支持
e.stopPropagation();//谷歌和火狐支持

window.event和e都是事件参数对象,一个是IE的标准,一个是火狐的标准
事件参数e在IE8的浏览器中是不存在,此时用window.event来代替

上面的例子就可以变成这样:为了省变篇幅只写JS部分

   //阻止事件冒泡函数
    function stopBubble(e) {
        if (e && e.stopPropagation)
            e.stopPropagation()
        else
            window.event.cancelBubble = true
    }

    var xy$ = function (id) {
        return document.getElementById(id)
    };
    xy$("bx1").onclick = function () {
        console.log(this.id)
    };
    xy$("bx2").onclick = function () {
        console.log(this.id)
    };
    xy$("bx3").onclick = function (e) {
        console.log(this.id);
        stopBubble(e)
    }

效果
在这里插入图片描述

事件阶段

1.事件捕获阶段:从外到内
2.事件目标阶段:选择的那个
3.事件冒泡阶段:从内到外

通过e.eventPhase这个属性返回事件传播的当前阶段
* 如果这个属性的值是:
* 1---->捕获阶段
* 2---->目标阶段
* 3---->冒泡
*

 	
    var xy$ = function (id) {
        return document.getElementById(id)
    };
    var objs = [xy$("bx3"), xy$("bx2"), xy$("bx1")];
    //遍历注册事件
    objs.forEach(function (ele) {
        //为每个元素绑定事件
        ele.addEventListener("click", function (e) {
            console.log(this.id + ":" + e.eventPhase);
        }, false);
    });


在这里插入图片描述

发布了166 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45020839/article/details/105030692