0172 事件对象 之 阻止事件冒泡:stopPropagation(),cancelBubble=true

事件冒泡本身的特性,会带来的坏处,也会带来的好处。

标准写法:利用事件对象里面的 stopPropagation()方法
e.stopPropagation() 

非标准写法:IE 6-8 利用事件对象 cancelBubble 属性
e.cancelBubble = true;

    <div class="father">
        <div class="son">son儿子</div>
    </div>
    <script>
        var son = document.querySelector('.son');
		// 给son注册单击事件
        son.addEventListener('click', function(e) {
            alert('son');
            e.stopPropagation(); // stop 停止  Propagation 传播
            window.event.cancelBubble = true; // 非标准 cancel 取消 bubble 泡泡
        }, false);

        var father = document.querySelector('.father');
		// 给father注册单击事件
        father.addEventListener('click', function(e) {
            alert('father');
            e.stopPropagation();
        }, false);

		// 给document注册单击事件
        document.addEventListener('click', function() {
            alert('document');
        })
    </script>

阻止事件冒泡的兼容性处理

    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }

posted on 2020-01-10 17:29  冲啊!  阅读(285)  评论(0编辑  收藏  举报

导航