这些日子我就把js的相关知识梳理一下,今天来说javascript中的事件流。

1.事件流

事件流:从页面中接收事件的顺序。也就是说当一个事件产生时,这个事件的传播过程,就是事件流。

  • IE的事件流

  IE中的事件流叫事件冒泡;事件冒泡:事件开始时由最具体的元素接收,然后逐级向上传播到较为不具体的节点(文档)。对于html来说,就是当一个元素产生了一个事件,它会把这个事件传递给它的父元素,父元素接收到了之后,还要继续传递给它的上一级元素,就这样一直传播到document对象(亲测现在的浏览器到window对象,只有IE8及下不这样);

再多说一句,现在的浏览器默认是采用的是事件冒泡;在DOM0级方法绑定事件只能是事件冒泡,不能设置;在DOM2级你可以设置是用事件冒泡还是事件捕获(下面说);

说了半天冒泡有可能没太听懂,上代码就知道了:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>事件冒泡</title>
  <style type="text/css">
  #child{
    background: red;
    width:50px;
    height:50px;
  }
  #father{
    width:100px;
    height:100px;
    background:green;
  }
  #grandparent{
    width:150px;
    height:150px;
    background:black;
    margin:100px auto 0;
  }
  </style>
</head>
<body>
  <div id='grandparent'>
    <div id='father'>
      <div id='child'></div>
    </div>
  </div>
</body>
<script type="text/javascript">
  var grandparent = document.getElementById("grandparent");
  var parent = document.getElementById("father");
  var child = document.getElementById('child');
  var html = document.getElementsByTagName("html")[0];
  var body = document.body;
  child.onclick = function () {
    console.log("我是儿子");
  }
  parent.onclick = function () {
    console.log("我是父亲");
  }
  grandparent.onclick = function () {
    console.log("我是爷爷");
  }

  window.onclick = function () {
    console.log("我是window");
  }
  document.onclick = function () {
    console.log("我是document");
  }
  html.onclick = function () {
    console.log("我是html");
  }
  body.onclick = function () {
    console.log("我是body");
  }
</script>
</html>
事件冒泡代码

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2021-10-22
  • 2021-08-26
  • 2021-08-09
  • 2021-07-22
相关资源
相似解决方案