js阻止默认事件和阻止事件冒泡的区别和兼容写法(event.preventDefault()和event.stopPropagation())

初期会把这两个搞混,今天去仔细看了一下说明。
相比较的说明一下

event.stopPropagation()

不让事件传递到父元素,停止事件冒泡(停止事件向上派发)。
例如:

<div class="box">
			<a href="index.html"  target="_blank">点击跳转</a>
</div>
<script>
			document.getElementsByTagName("a")[0].onclick=function(e){
				e.stopPropagation();
			}
			document.getElementsByTagName("div")[0].onclick=function(){
				console.log("被传递");
			}
			上面的代码不会输出“被传递”,但是还是会跳转到index.html页面,阻止了onclick的事件冒泡到父元素上。
			如果不加e.stopPropagation();即会跳转也会输出“被传递”。
			接着用event.prevnentDefault()对比一下
</script>

阻止事件冒泡比较常用,像是做一个点击input框显示一个信息框,然后点其他地方隐藏,这时候我们基本都会给document一个点击事件,如果不阻止事件冒泡信息框就不会显示。

event.preventDefault()

取消被触发元素的默认事件。
例如:

<div class="box">
			<a href="index.html"  target="_blank">点击跳转</a>
</div>
<form action="index.html">
			<input type="submit" value="提交" />
</form>
<script>
			document.getElementsByTagName("a")[0].onclick=function(e){
				e.preventDefault();
			}
			document.getElementsByTagName("div")[0].onclick=function(){
				console.log("被传递");
			}
			点击a标签不会跳转,虽然取消了a标签的默认跳转,但是会输出“被传递”。
			document.getElementsByTagName("input")[0].onclick=function(){
				event.preventDefault();
			}
			点击提交按钮也不会跳转,因为取消了submit的默认提交事件
</script>

还有一个小知识点:
return false;在原生js中只会阻止默认事件不会阻止事件冒泡,jQuery即取消默认事件也阻止事件冒泡

兼容性

知道了区别和用法接着就是了解方法的兼容性
说明白就是兼容IE6,7,8,9呗
e.stopPropagation(),IE使用的是e.cancelBubble = true

document.getElementsByTagName("a")[0].onclick=function(e) { 
if (e&&e.stopPropagation){//如果条件满足,则这是一个非IE浏览器 
    e.stopPropagation(); //阻止事件冒泡
}else{ //否则,需要使用IE的方式来取消事件冒泡 
    window.event.cancelBubble = true; 
    }
}

e.preventDefault(),IE则是使用e.returnValue = false;

document.getElementsByTagName("a")[0].onclick=function(e) { 
if (e&&e.preventDefault){//如果条件满足,则这是一个非IE浏览器 
    e.preventDefault(); //取消默认事件
}else{ //否则,需要使用IE的方式来取消默认事件
    window.event.returnValue = false;
    }
}
发布了31 篇原创文章 · 获赞 45 · 访问量 5907

猜你喜欢

转载自blog.csdn.net/weixin_43623808/article/details/102765396