DOM-event bubbling (Bubble)


What is bubbling?

       If I am a little boy and I like a little girl in my class very much, one day I couldn't help but kiss her, and then she beat me up, she went back and told her father, and the little girl's father also Angrily, she found me and beat me up. At the dinner table in the evening, her father told the little girl's grandfather about it. Her grandfather found me and beat me up before he even finished his meal. Oh, it's not worth it. , I kissed her and was beaten three times. The so-called bubbling refers to the upward transmission of events. When an event on a descendant element is triggered, the same event on its ancestor element will also be triggered. In most cases, bubbling is useful in development.


Tip: The following is the text of this article, and the following cases are for reference

1. How to cancel bubbling?

       After I kissed the little girl and she beat me up, I hoped she wouldn't tell her dad, so I asked her if she could be my girlfriend, and she said yes so I wouldn't have to be beaten.

       If you do not want event bubbling to occur, you can cancel the bubbling through the event object, and set the cancelBubble of the event object to true to cancel the bubbling.

2. Case Analysis

1. Full text code

The code is as follows (example):

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>事件冒泡(Bubble)</title>
		<style type="text/css">
			#box1{
    
    
				height: 200px;
				width: 200px;
				background-color: deepskyblue;
			}
			#s1{
    
    
				background: blueviolet;
			}
			*:hover{
    
    
				cursor: pointer;
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
    
    				
				//为span绑定单击响应函数
				var span = document.getElementById("s1");
				span.onclick = function(event){
    
    
					
				//解决兼容性
				event = event || window.event;
				
				alert("我是span");
				
				/*取消冒泡*/					
				event.cancelBubble = true;
				};
				
				//为span绑定单击响应函数
				var div = document.getElementById("box1");
				div.onclick = function(event){
    
    
					//解决兼容性
					event = event || window.event;
					alert("我是div");					
					/*取消冒泡*/					
					event.cancelBubble = true;
				};
				
				//为span绑定单击响应函数
				document.body.onclick = function(){
    
    
					alert("我是body");
				};
			};
		</script>
	</head>
	<body>
		<div id="box1">
			我是div
			<span id="s1">我是span</span>
		</div>
	</body>
</html>

2. Key parts

The code is as follows (example):

//为span绑定单击响应函数
	var span = document.getElementById("s1");
	span.onclick = function(event){
    
    		
		//解决兼容性
		event = event || window.event;		
		alert("我是span");		
		/*取消冒泡*/					
		event.cancelBubble = true;
	};

Summarize

       Bubbling is still very useful for most programs, but only a small part of the place does not need bubbling, so it depends on your own needs when dealing with this problem.

Guess you like

Origin blog.csdn.net/qq_46665317/article/details/108021359