html 阻止重叠事件触发

实际上是事件冒泡的知识点,用更通俗的方式起的标题。

测试页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div onclick="test1(1, event)" style="width:200px;height:200px;border: 1px solid black">
			<div onclick="test2(2, event)" style="width:100px;height:100px;border: 1px solid red">
				<div onclick="test3(3, event)" style="width:50px;height:50px;border: 1px solid blue">
					<a onclick="test4(4, event);" href="Test45.html">aaa</a>
				</div>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		function test1(v, event){
			console.log(v);
		}
		function test2(v, event){
			console.log(v);
		}
		function test3(v, event){
			console.log(v);
		}
		function test4(v, event){
			console.log(v);
		}
		console.log("init");	
	</script>
</html>

在这里插入图片描述
简单来说,事件的触发是从内向外的。如果点击了最内层的a标签,控制台会依次输出4,3,2,1 ,点击蓝色div,会输出3,2,1。点击事件会全部触发,但是有时候我们需要在触发内层后,不触发外层事件,这时需要用到stopPropagation函数。

将上述test4改成这样

		function test4(v, event){
			console.log(v);
			event.stopPropagation();
		}

当点击a标签后,控制台只会输出4 。
event.stopPropagation(); 也可以写成event.cancelBubble = true;

顺便再介绍另一个方法event.preventDefault(); 。它阻止的是事件的默认动作,这个默认动作具体来说就是,a标签对应的href(跳转),submit的提交一类的。

举个例子

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div onclick="test1(1, event)" style="width:200px;height:200px;border: 1px solid black">
			<div onclick="test2(2, event)" style="width:100px;height:100px;border: 1px solid red">
				<div onclick="test3(3, event)" style="width:50px;height:50px;border: 1px solid blue">
					<a onclick="test4(4, event);" href="Test45.html">aaa</a>
				</div>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		function test1(v, event){
			console.log(v);
		}
		function test2(v, event){
			console.log(v);
		}
		function test3(v, event){
			console.log(v);
		}
		function test4(v, event){
			console.log(v);
			event.stopPropagation();
		}
		console.log("init");
	</script>
</html>

点击a标签后,控制台会打出4,3,2,1,但是不会触发href="Test45.html"的跳转。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章