js阻止事件冒泡附案例

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		* {
			margin: 0;
			padding: 0;
		}
	</style>
</head>

<body>
	<div class="a" style="width: 100px;height: 100px;background: red;" onclick="a()">
		<div class="b" style="width: 20px;height: 20px;background: green;" onclick="b('1')"></div>
	</div>
	<script>
		function a() {
			console.log('a');
		}
		//点击button的方法
		function b(a, event) {
			console.log(a);
			console.log('b');
			stopBubbling(event);
		}

		function stopBubbling(e) {
			e = window.event || e;
			if (e.stopPropagation) {
				e.stopPropagation(); //阻止事件 冒泡传播
			} else {
				e.cancelBubble = true; //ie兼容
			}
		}
	</script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_41111677/article/details/108087669
今日推荐