淺談js之事件流

來源:互聯網
上載者:User

淺談js之事件流
這些日子我就把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>

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.