[前端] e.stopPropagation()阻止事件冒泡

事件冒泡:是由具体元素逐一向父级冒泡 div->body->document

事件捕获:是由文档最外层逐一向具体捕获 document->body->div 


ele.addEventListener('click', func, true)

true 捕获

false 冒泡


实例(这里写的是一个弹出层):

CSS样式:

 <style> * { margin: 0; padding: 0; } button { width: 100px; height: 100px; border-radius: 50%; background: #0bd38a; font-size: 24px; color: #fff; outline: none; cursor: pointer; } .modal-wrap { display: none; position: fixed; left: 0; top: 0; z-index: 999; width: 100%; height: 100%; background: rgba(0,0,0,0.5); } .modal { width: 600px; height: 350px; margin: 150px auto 0; border-radius: 5px; background: #fff; box-shadow: 0 0 5px #666; } .modal-title { position: relative; height: 45px; padding: 0 10px; border-top-left-radius: 5px; border-top-right-radius: 5px; background: #0bd38a; line-height: 45px; } .modal-title h2 { font-size: 18px; color: #fff; } .modal-title i { position: absolute; right: 20px; top: 0; font-style: 18px; color: #fff; font-style: normal; font-weight: bold; cursor: pointer; } .modal-body { padding: 10px; } </style>


HTML布局:

 <button type="button">点击</button> <div class="modal-wrap"> <div class="modal"> <div class="modal-title"> <h2>弹出层</h2> <i>X</i> </div> <div class="modal-body"> 这是一个测试 </div> </div> </div>


JS脚本:

实现的功能是点击透明区域也会关闭对话框

 <script> // 占击按钮弹出对话框  $('button').click(function() { $('.modal-wrap').fadeIn(); }); // 点击X号隐藏对话框  $('.modal-title i').click(function() { $(this).parents('.modal-wrap').fadeOut(); }); /* 方法一 */  // 点击对话框外区域隐藏对话框  /*$('body').click(function() {  $('.modal-wrap').fadeOut();  });*/   // 点击对话框内部/按钮阻止事件冒泡  /*$('.modal, button').click(function(e) {  e.stopPropagation();  });*/    /* 方法二(推荐) */  // 点击透明区域隐藏对话框  $('.modal-wrap').click(function() { $(this).fadeOut(); }); // 点击对话框内部阻止事件冒泡  $('.modal').click(function(e) { e.stopPropagation(); }); </script>


谢谢关注!


你可能感兴趣的:(js)