JS event three stages

The main event of the process has three phases: the capture phase, the goal stage, bubbling phase;
1. capture phase
when we bind the event to an element, go through the pre-event trigger event capture stage
as shown in
Here Insert Picture Description
us to register a div click event when the event will go through the capturing phase, the event has been found to bind elements of the current events from the outermost layer referred to here as the event target capture stage, and then trigger a click event ().
2. Objectives stage
when the event from the outermost continuously delivered to the target node, the final trigger event in the destination node.
3. Event bubbling
when the event is triggered, layer by layer will be coming out to the outermost element here is exactly the opposite event capture
Here Insert Picture Description
us look at an example

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		#one {
			width:300px;
			height:200px;
			background: red
		}
		#two {
			width:250px;
			height:150px;
			background: blue
		}
		#three{
			width:200px;
			height:100px;
			background: orange
		}
	</style>
</head>
<body>
	<div id='one'>one
		<div id='two'>two
			<div id='three'>three</div>
		</div>
	</div>

</body>
<script type="text/javascript">
	var three = document.getElementById('three');
	one.onclick=function(){
		console.log('one')
		
	}
	two.onclick=function(){
		console.log('two')
		
	}
	three.onclick=function(){
		console.log('three')
		
	}
	
	
</script>
</html>

We give three were registered div click event, when we click on the innermost div.
Here Insert Picture Description
Output three times, this is because of event bubbling, when the innermost div click event will be one level coming out
due to the three div bound to the same type of event so each element is performed once.

Note that we ordinary registered events are executed in the event bubbling phase
such as onclick, mouseover. And so on
but mouseenterand mouseleavedoes not trigger the event bubbling

Sometimes we do not want to perform in the bubbling stage of the event, how do?
1. provided by the event object stopPropagation()method

three.onclick=function(e){
		console.log('three');
		e.stopPropagation();//停止
	}

2. addEventListenerYou can modify the third parameter is the event registration event decided to perform the capture or bubbling phase
true event capture
false event bubbling

Clear element default behavior e.preventDefault()

Published 58 original articles · won praise 1 · views 2154

Guess you like

Origin blog.csdn.net/weixin_45143481/article/details/104512903