阻止冒泡
w3c的方法是event.stopPropagation(),IE则是使用event.cancelBubble = true;
兼容写法
<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标签点击事件的默认行为都无法执行,也就是都无法跳转。
兼容写法
<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的话则既阻止默认行为又防止对象冒泡。
<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;
});
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。