DOM事件,捕获和冒泡 自定义事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Event</title>
	</head>
	<body>
		<div id="ev">
			<style type="text/css">
				#ev{
					width: 300px;
					height: 100px;
					background: red;
					color: #fff;
					text-align: center;
					line-height: 100px;
				}
			</style>
			目标元素
		</div>
		<script type="text/javascript">
			
			// addEventListener() 函数后面为true捕获 为false冒泡
			var ev = document.getElementById('ev');
			
			window.addEventListener('click',function(){
				console.log('window captrue')
			},false);
			
			document.addEventListener('click',function(){
				console.log('document captrue')
			},false);
			
			document.documentElement.addEventListener('click',function(){
				console.log('html captrue')
			},false);
			
			document.body.addEventListener('click',function(){
				console.log('body captrue')
			},false);
			
			ev.addEventListener('click',function(){
				console.log('ev captrue')
			},false)
		</script>
	</body>
</html>

如上列所示,为冒泡事件。可以直接复制代码运行,刷新点击可以在打印出冒泡事件的

 当把函数后面的false改为true时,则为捕获事件,此时,刷新点击目标元素,答应打印顺序如下

 

 最后就是dom的自定义事件

// 自定义事件
			var eve = new Element('test');
			ev.addEventListener('test',function(){
				console.log('test dispatch')
			})
			ev.dispatchEvent(eve);

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值