事件的阻止冒泡和阻止默认行为

阻止冒泡

w3c的方法是event.stopPropagation(),IE则是使用event.cancelBubble = true;javascript

兼容写法

<div class="parent">
  <div class="child"></div>
</div>
<script>
  const child = document.querySelector(".child");
  child .addEventListener("click",function(event){
    event = window.event || event
    if(event.stopPropagation){
      event.stopPropagation()
    }else{
      event.cancelBubble = true
    }
  })    
</script>

阻止默认行为

w3c的方法是event.preventDefault(),IE则是使用event.returnValue = false;
若是事件是能够冒泡的,在冒泡过程当中也能够阻止默认行为,举个例子,咱们在body标签的click事件中阻止默认行为,那么页面上全部的a标签点击事件的默认行为都没法执行,也就是都没法跳转。java

兼容写法

<input id="div" value="123">
  <script>
  const div = document.getElementById("div")
  div.addEventListener("copy",function(event){
    event = window.event || event;
    if(event.preventDefault){
      event.preventDefault()
    }else{
      event.returnValue = false;
    }
  })
  </script>

return false

javascript的return false只会阻止默认行为,且只能在dom0事件中生效。
而用jQuery的话则既阻止默认行为又防止对象冒泡。dom

<a href="www.baidu.com" id="a"></a>
const a = document.getElementById("a")
a.onclick = function(){
    return false;
};
<a href="www.baidu.com" id="a"></a>
$("#a").on('click',function(){
return false;
});
相关文章
相关标签/搜索