美文网首页
事件捕获和冒泡

事件捕获和冒泡

作者: DearVi | 来源:发表于2020-04-19 22:25 被阅读0次

onclick 事件 执行顺序 先子后父 冒泡执行


image.png
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="text/javascript">
      function onSonClick() {
        console.log("onSonClick");
      }
      function onFatherClick() {
        console.log("onFatherClick");
        document.getElementById('son').click();
      }
    </script>
  </head>
  <body>
    <div
      id="father"
      style="width: 200px; height: 200px; background-color: green;"
      onclick="onFatherClick()"
    >
      <div
        id="son"
        style="width: 100px; height: 100px; background-color: yellow;"
        onclick="onSonClick()"
      ></div>
    </div>
  </body>
</html>
image.png

对一个元素document.addEventListener方法可以多次添加,会执行多次,onclick方法赋值已最后一次为准。addEventListener第三个参数表示触发是在捕获阶段还是冒泡阶段触发。如果元素既有onclick 和 Event click事件,已经是最内层的元素了先执行onclick事件,然后才是caputure 和bubbing,顺序是caputure>onclick>bubbing。如果不是最内层的元素则顺序是caputure>onclick>bubbing.

下面是网上看到关于attachEvent和addEvenLisenter的兼容性
attachEvent——兼容:IE7、IE8;不兼容firefox、chrome、IE9、IE10、IE11、safari、opera
addEventListener——兼容:firefox、chrome、IE、safari、opera;不兼容IE7、IE8。

事件类型:UIEvent、FocusEvent、MouseEvent、WheelEvent、KeyboardEvent、CompositionEvent

load、unload、abort、error、select、resize、scroll

blur、focus、focusin、focusout。

鼠标事件共有11种类型,分别是click、contextmenu、dblclick、mousedown、mouseup、mousemove、mouseover、mouseout、mouseenter、mouseleave和onmousewheel shift键盘和点击时触发e.shiftKey

wheel

onkeydown,onkeyup keypress

compositionstart、compositionupdate、compositionend。

相关文章

网友评论

      本文标题:事件捕获和冒泡

      本文链接:https://www.haomeiwen.com/subject/oxiebhtx.html