事件冒泡与事件捕获

事件冒泡:结构上(非视觉上)嵌套关系的元素,会存在事件冒泡的功能,即同一事件,自子元素冒泡向父元素。(自底向上)

css:
#container{
            width:300px;
            height:300px;
            background:red;
        }
        #father{
            width:200px;
            height:200px;
            background:green;
            margin-left:300px;
        }
        #son{
            width:100px;
            height:100px;
            background:blue;
            margin-left:200px;
        }
html:
     <div id="container">
        <div id="father">
            <div id="son"></div>
        </div>
    </div>
js:
     container.addEventListener('click',function(){
            console.log('container bubble')
        },false)
        father.addEventListener('click',function(){
            console.log('father bubble')
        },false)
        son.addEventListener('click',function(){
            console.log('son bubble')
        },false)
 //执行顺序 son bubble ,father bubble, container bubble

事件捕获:(只有谷歌有,最新火狐有,IE没有捕获事件)结构上(非视觉上)嵌套关系的元素,会存在事件捕获的功能,即同一事件,自父元素捕获至子元素(事件源元素)。(自底向上)

		container.addEventListener('click',function(){
            console.log('container ')
        },true)
        father.addEventListener('click',function(){
            console.log('father')
        },true)
        son.addEventListener('click',function(){
            console.log('son')
        },true)
        //执行顺序 container , father, son 

注意:触发事件元素son的冒泡和捕获事件是先看谁触发的(即从上往下谁先绑定的,谁就先触发事件,冒泡事件先绑定,先触发son bubble)

       container.addEventListener('click',function(){
            console.log('container bubble')
        },false)
        father.addEventListener('click',function(){
            console.log('father bubble')
        },false)
        son.addEventListener('click',function(){
            console.log('son bubble')
        },false)
        container.addEventListener('click',function(){
            console.log('container ')
        },true)
        father.addEventListener('click',function(){
            console.log('father')
        },true)
        son.addEventListener('click',function(){
            console.log('son')
        },true)
        //执行顺序 container,
        //         father, 
        //         son bubble, 
        //         son, 
        //         father bubble, 
        //         container bubble

阻止事件冒泡:e.stopPropagation();
       e.canceBubble=true;(IE9之前使用)
阻止默认事件:e.preventDefault();句柄方式绑定事件,则用return false;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值