jQuery事件冒泡程式碼例項

螞蟻小編發表於2017-04-14

分享一段程式碼例項,它演示了事件冒泡的相關特性。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
body {
  padding: 0;
  margin: 0;
  width: 1024px;
  height: 768px;
  background-color: #c3c3c3;
  overflow: hidden;
  position: relative;
}
.button {
  width: 50px;
  height: 50px;
  top: 200px;
  left: 200px;
  position: absolute;
  background-color: aquamarine;
}
.refcontent {
  width: 100px;
  height: 100px;
  top: 300px;
  left: 300px;
  position: absolute;
  background-color: red;
  display: none;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(document).ready(function(){
  $('.button').on('click',function(e){
    $('.refcontent').toggle();
    e.stopPropagation();
  });
  $('body').click(function(){
    $('.refcontent').hide();
  });
  $('.refcontent').on('click',function(e){
    e.stopPropagation();
  });
});
</script>
</head>
<body>
<div class="button"></div>
<div class="refcontent"></div>
</body>
</html>

上面的程式碼實現了簡單的演示,下面簡單做一下介紹。

[JavaScript] 純文字檢視 複製程式碼
$('.button').on('click',function(e){
  $('.refcontent').toggle();
  e.stopPropagation();
})

點選此div可以實現refcontent的顯示和隱藏的切換,如果沒有e.stopPropagation()這段程式碼,那麼refcontent永遠都不會彈出來,因為click事件會冒泡到body,於是註冊在body的click事件處理函式就會執行,就會將refcontent隱藏。

相關閱讀:

(1).事件冒泡可以參閱什麼是jquery事件冒泡一章節。

(2).stopPropagation()可以參閱jQuery event.stopPropagation()一章節。

相關文章