事件冒泡和事件捕获和事件委托

#####1.、事件冒泡
A、在默认情况下,事件采用冒泡事件处理,不使用事件捕获,在firefox和safari里面,你可以设置useCapture参数(***addEventListenner(‘click’,function(){},useCapture)***) ,将这个参数设为true。


参考代码如下:

<div onclick="three()" id="three">
        <div onclick="two()" id="two">
            <div onclick="one()" id="one">
                点击我
            </div>
        </div>
</div>
<script type="text/javascript">
    function three() {
        alert('盒子 3 被触发');
    }
    function two() {
        alert('盒子 2 被触发');
    }
    function one(){
        alert('盒子 1 被触发');
        //window.event?window.event.cancelBubble = true:event.stopPropagation();
        //阻止事件冒泡
}
</script>

B、其中阻止事件冒泡代码中,首先判断是否是IE

window.event.cancelBubble = true  //IE阻止冒泡事件
event.stopPropagation()           //非IE阻止冒泡事件

####2、事件捕获
A、事件捕获是非IE浏览器的专属(IE11已经支持事件捕获),事件触发的过程是从外层的容器一层一层的向目标元素触发,本例中共有三层div嵌套组成,为了兼容IE低版本,代码中添加了attachEvent方法。

<div id="three">
    <div id="two">
        <div id="one">
            点击我
        </div>
    </div>
</div>
<script type="text/javascript">
    var one = document.getElementById("one");
    var two = document.getElementById("two");
    var three = document.getElementById("three");
    one.attachEvent?one.attachEvent('onclick',function(){  //attachEvent方法兼容IE11以下版本
        alert(" one  IE!");
    }):one.addEventListener('click',function(){            //非IE采用addEventListener方法可以选择触发方式是冒泡还是捕获,最后一位参数为true时是事件捕获,反之则为事件冒泡。
        alert("one");
    },true);
    two.attachEvent?two.attachEvent('onclick',function(){
        alert("two  IE!");
    }):two.addEventListener('click',function(){
        alert("two");
    },true);
    three.attachEvent?three.attachEvent('onclick',function(){
        alert(" three IE!");
    }):three.addEventListener('click',function(){
        alert("three");
    },true);
</script>

B、注意

       attachEvent('onclick',fn)方法只有两个参数,也正因为如此,IE低版本中只能触发冒泡useCapture
       addEventListener('click',fn,useCapture)方法有三个参数,非IE浏览器在最后一位参数为true时采用事件
捕获,为false时采用事件冒泡,***IE11已经支持该方法***。

####3、事件委托
A、事件委托是基于事件冒泡的,本来需要给子元素添加的事件转移到父元素上面,然后判断操作的是哪一个子元素进行相应的操作


<div onclick="eventHandle(event)" id="three">
    <div id="two">
        <div id="one"></div>
    </div>
</div>
<script type="text/javascript">
    function eventHandle(e) {
        var e = e||window.event;
        var obj = e.target||e.srcElement;
        alert(obj.id+' 被点击')
    }
</script>

B、注意
非IE下的目标元素获取采用 ***event.target***方法获取。IE下的目标元素获取采用***window.event.srcElement***方法获取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值