JS事件传播流程-学习笔记

JS事件传播流程-学习笔记

一、事件传播三个阶段

1、 捕获阶段
2、 目标阶段
3、 冒泡阶段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #grafather{width: 500px;height: 300px;background-color: teal;margin: auto;}
        #father{width: 400px;height: 200px;background-color: yellowgreen;margin: auto;}
        #me{width: 300px;height: 100px;background-color: tomato;margin: auto;}
        #son{width: 200px;height: 50px;background-color: salmon;margin: auto;}
    </style>
</head>
<body>
    <div id="grafather" ondblclick="grafa()">
        grafather
        <div id="father">
            father
            <div id="me">
                me
                <div id="son">
                    son
                </div>
            </div>
        </div>
    </div>
    <script>
        // html事件
        function grafa() {
            console.log("grafather");
        }
        // DOM 0级事件
        var fath=document.getElementById("father");
        fath.onclick=function(){
            console.log("father");
        }
        // DOM 2级事件
        var me=document.getElementById("me");
        me.addEventListener("click",showme,false);
        function showme() {
            console.log("me");
        }
    </script>
</body>
</html>

二、事件绑定(事件处理)三种方式

1、 HTML标签
在这里插入图片描述
2、 DOM 0级
在这里插入图片描述
3、 DOM 2级(事件监听)
在这里插入图片描述

三、问题:捕获和冒泡的设定

DOM2级事件绑定,使用addEventListener第三个参数useCapture是可以设置事件是在捕获阶段执行(true)还是在冒泡阶段执行(false),那么,html标签和dom0级事件,是否可以设置?找了半天也没有确定的答案,唯一可以稍微确定的是,前两个事件都在冒泡阶段执行。当点击me时,捕获阶段没有事件,到me后,冒泡开始,从内到外依次执行me-father-grafather。
在这里插入图片描述

四、事件传播过程,都传播了什么?

1、 我直观的理解,事件的传播过程,将鼠标点击事件click从外到内传递,当我把grafather的事件改为ondblclick,点击father或me时,grafather没有执行。
在这里插入图片描述
2、 参看https://blog.csdn.net/qq_23389687/article/details/80166843,DOM0和DOM2级事件

3、补充,回头看了事件,一个事件发生后,会生成一个事件对象event,对象里包含了各种信息,包括鼠标点击的屏幕X,Y坐标点,事件的动作。有一个属性path,记录了事件的观光旅游路径。所以我想,既然找到了事件的目标元素等所有信息,为什么不直接执行呢?为什么还要绕一大圈,从上到下又从下到上来一回?而且,如果你不想事件传递,只在点击元素执行事件,可以stopPropogation。不知道ie和netscape当年为什么有此争论,我再去看看。

五、让事件在捕获阶段执行

将4个div全部用addEventListener绑定click事件,并设置为捕获阶段执行
在这里插入图片描述
点击son时,从grafather开始执行
在这里插入图片描述
将grafather和me设置为冒泡,另两个设置为捕获
在这里插入图片描述

六、事件委托

<ul onclick="ulclick()">
       <li>1</li>
       <li>2</li>
       <li>3</li>
       <li>4</li>
       <li>5</li>
       <span>aaaa</span>
     </ul>
   <script>
      ulclick=()=>{
          if (event.target.tagName=='LI') {
              console.log(event.target.innerHTML);
          }
      }
   </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值