事件的传播——JS

事件的传播

事件传播分成了三个阶段

1.捕获阶段
在捕获阶段时从最外层的祖先元素,向目标元素进行事件的捕获,但是默认此时不会触发事件

2.目标阶段
事件捕获到目标元素,捕获结束开始在目标元素上触发事件

3.冒泡阶段
事件从目标元素向他的祖先元素传递,依次触发祖先元素上的事件

在这里插入图片描述

  • 如果希望在捕获阶段就触发事件,可以将addEventListener()的第三个参数设置为true,一般情况下不会使用。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        #box1{
            width: 300px;
            height: 300px;
            background-color: pink;
        }
        #box2{
            width: 200px;
            height: 200px;
            background-color: rgb(172, 80, 95);
        }
        #box3{
            width: 150px;
            height: 150px;
            background-color: rgb(100, 9, 24);
        }
    </style>
    <script>
        window.onload= function(){
            var box1 = document.getElementById("box1");
            var box2 = document.getElementById("box2");
            var box3 = document.getElementById("box3");

            bind(box1,"click",function(){
                alert("我是box1");
            });
            bind(box2,"click",function(){
                alert("我是box2");
            });
            bind(box3,"click",function(){
                alert("我是box3");
            });



        };

        function bind(obj, eventStr, callback){

            if(obj.addEventListener){
            //    大部分浏览器兼容的方式
            obj.addEventListener(eventStr, callback, true);
            }else{
            // IE8及以下
            obj.attachEvent("on"+eventStr, function(){
                callback.call(obj);
            });

            // 修改this的方法:
            // 在匿名函数中调用callback(),拿回函数的调用权
            // 再通过call(对象)替换this

            }
           } 

    </script>

</head>
<body>
    <div id="box1">
        <div id="box2">
            <div id="box3">
            </div>
        </div>
    </div>
    
</body>
</html>

点击box3

输出:

我是box1;

我是box2;

我是box3;

  • IE8及以下的浏览器中没有捕获阶段
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值