JavaScrip中的事件的冒泡和捕获,事件绑定,事件的移除

一.事件的冒泡和事件的捕获
1.事件流描述的是从页面中接受事件的顺序。 事件流包括事件的冒泡和事件的捕获

事件的捕获:父级元素先触发,子集元素后触发。
事件的冒泡:子集元素先触发,父级元素后触发。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#father{
				width: 200px;
				height: 200px;
				background: deepskyblue;
				border: 1px solid deepskyblue;
			}
			#son{
				width: 100px;
				height: 100px;
				background: deeppink;
				margin: 50px auto;
			}
		</style>
		<script type="text/javascript">				
			window.onload=function(){
				var Father=document.getElementById('father');
				//Father.innerHTML='第一个div是父元素';
				var Son=document.getElementById('son');
				//Son.innerHTML='第二个div是子元素';
				var arr=[Son,Father,document,document.body];
				for(var i=0;arr.length;i++){
				//传统方式绑定事件的  事件的传播的方式就是冒泡排列
					/*arr[i].onclick=function(){
						console.log(this);  //子元素先触发,父元素后触发
					}
				}*/
				//第三个参数flase表示的事件的冒泡
					/*arr[i].addEventListener('click',function(){
						console.log(this);
					},false);*/
				//第三个参数true表示的事件的捕获
					arr[i].addEventListener('click',function(){
						console.log(this);
					},true);
				}
				
			}
		</script>
	</head>
	<body>
		<div id="father">
			<div id="son"></div>
		</div>		
	</body>
</html>

2.事件的绑定
语法:element.addEventListener(event,function, useCapture);
第一个参数是事件的类型:(如’click’或者‘mousedown’)
第二个参数是事件触发后调用的函数
第三个参数是个布尔值用于描述事件是冒泡还是捕获。该参数是可选的。

	<script>
		window.onload=function(){
			var Btn1=document.getElementById('btn1');
			var Btn2=document.getElementById('btn2');		
			//传统方式:只能触发第二个 
			/*Btn1.onclick=function(){
				console.log('第一个');
			}
			Btn1.onclick=function(){
				console.log('第二个');
			}*/
			//添加监听事件
			//addEventlistener  添加事件监听器
			//type listener useCapture  事件类型  事件处理程序    事件的捕获或者冒泡
			  
			//事件的冒泡两个都可以输出  
			Btn1.addEventListener('click',function(){
			 	console.log('第一个');
			 },false);
			Btn1.addEventListener('click',function(){
				console.log('第二个')
			},false);   
			
			
		}
			
		</script>
	</head>
	<body>
		<button id="btn1">按钮1</button>
		<button id="btn2">按钮2</button>
	</body>

3.事件的移除

<script>
			window.onload=function(){
				var Btn1=document.getElementById('btn1');
				var Btn2=document.getElementById('btn2');
				//传统移除事件的方法
				/*Btn1.onclick=function(){
					console.log('第一人')
				}
				Btn2.onclick=function(){
					console.log('第二人');
				}
				Btn1.onclick=null;*/
				//移除事件,不能使用匿名函数
				 Btn2.addEventListener('click',fn1,false);
				 function fn1(){
				 	console.log('第二个人');
				 }
				 //移除事件监听器
				 Btn2.removeEventListener('click',fn1,false);
			}
		</script>
	</head>
	<body>
		<button id="btn1">按钮1</button>
		<button id="btn2">按钮2</button>
	</body>

猜你喜欢

转载自blog.csdn.net/weixin_44269204/article/details/89478565
今日推荐