事件捕获与事件冒泡

事件传播模型:事件捕获和事件冒泡两个过程

即事件先到达根元素,再从根元素一层一层向下传播到目标元素,然后再一层一层向上传到根元素。

<div id='one'>
one
	<div id='two'>
	two
		<div id='three'>
		three
			<div id='four'>
			four
			</div>
		</div>
	</div>
</div>
<script type='text/javascript'>
	var one=document.getElementById('one');
	var two=document.getElementById('two');
	var three=document.getElementById('three');
	var four=document.getElementById('four');
	one.addEventListener('click',function(){
		alert('one');
	},true);
	two.addEventListener('click',function(){
		alert('two');
	},true);
	three.addEventListener('click',function(){
		alert('three');
	},true);
	four.addEventListener('click',function(){
		alert('four');
	},true

这几个事件处理程序都是在事件捕获阶段触发。

单击one:目标元素是one,输出one

单击two:目标元素是two,接收事件的顺序是one->two->one,因为只在捕获阶段处理事件,因此输出的是one two

单击three:目标元素是three,接收事件的顺序是one->two->three->two->one,因为只在捕获阶段处理事件,因此输出 one two three

单击four:目标元素是four,接收事件的顺序是one->two->three->four->three->two->one,因为只在捕获阶段处理事件,因此输出的是one two three four

	one.addEventListener('click',function(){
		alert('one');
	},false);
	two.addEventListener('click',function(){
		alert('two');
	},false);
	three.addEventListener('click',function(){
		alert('three');
	},false);
	four.addEventListener('click',function(){
		alert('four');
	},false);

单击one:输出one

单击two:输出two one

单击three:输出three two one

单击four:输出four three two one

	one.addEventListener('click',function(){
		alert('one');
	},true);
	two.addEventListener('click',function(){
		alert('two');
	},false);
	three.addEventListener('click',function(){
		alert('three');
	},false);
	four.addEventListener('click',function(){
		alert('four');
	},true);

单击four:输出one four three two

	one.addEventListener('click',function(){
		alert('one capture');
	},true);
	two.addEventListener('click',function(){
		alert('two bubble');
	},false);
	two.addEventListener('click',function(){
		alert('two capture');
	},true);
	three.addEventListener('click',function(){
		alert('three bubble');
	},false);
	four.addEventListener('click',function(){
		alert('four capture');
	},true);

事件的执行次数:绑定了几个事件就执行几次

这个分两种情况讨论:

(1)若目标元素是two,目标事件处理程序按添加事件的顺序执行,其他元素的按先捕获后冒泡

则输出:one capture--two bubble--two capture

(2)若目标元素不是two,假设单击four

则输出是:one capture--two capture--four capture--three bubble--two bubble
 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值