stopPropagation的研究

209 阅读1分钟

MDN上的描述: The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method.

stopPropagation 会阻止事件的传播。

  • 默认事件注册的函数都在冒泡阶段触发,此时在子元素上加上 event.stopPropagation() ,则可以阻止该事件(在冒泡阶段)触发到父元素上注册的函数
  • 如果手动将addEventListener的第三个参数改成true,即在捕获阶段触发事件注册的函数,那么在父元素上加event.stopPropagation() 则可以阻止事件(在捕获阶段)触发到子元素上注册的函数

demo1:阻止事件向上冒泡

<div class="outer" id="outer">
        <div class="inner" id="inner"></div>
</div>
<script>
  document.querySelector('#outer').addEventListener('click',function(event){
    alert('注册在outer上的事件回调')  // 这里执行不到
  },false) // 默认false,即在冒泡阶段触发事件注册的函数

  document.querySelector('#inner').addEventListener('click',function(event){
    alert('注册在inner上的事件回调');
    event.stopPropagation(); // 这里阻止了冒泡,就不会触发父元素outer对click事件注册的函数
  },false)
</script>

demo2:阻止事件向下捕获

<div class="outer" id="outer">
  <div class="inner" id="inner"></div>
</div>
<script>
  document.querySelector('#outer').addEventListener('click',function(event){
    alert('注册在outer上的事件回调')
    event.stopPropagation(); // 这里阻止事件向下冒泡,就不会触发子元素inner对click事件注册的函数
  },true) 

  document.querySelector('#inner').addEventListener('click',function(event){
    alert('注册在inner上的事件回调');  // 这里执行不到
  },true)
</script>

首发于:www.caishuxiang.com/?p=128