鹹魚前端—js 事件捕獲/冒泡

鹹魚前端—js 事件捕獲/冒泡

事件冒泡

事件冒泡:多個元素嵌套,有層次關係,這些元素註冊了相同的事件。裏面的元素的事件出發後,外面的元素的該事件也自動觸發。
例如:

<!DOCTYPE html>
<html>
<head>
    <title>冒泡車測試</title>
    <style type="text/css">
        #bx1 {
            width: 400px;
            height: 400px;
            background-color: red;
        }

        #bx2 {
            width: 300px;
            height: 300px;
            background-color: blue;
        }

        #bx3 {
            width: 200px;
            height: 200px;
            background-color: yellow;
        }

    </style>
</head>
<div id="bx1">
    <div id="bx2">
        <div id="bx3"></div>
    </div>
</div>
<script>
    var xy$ = function (id) {
        return document.getElementById(id)
    }
    xy$("bx1").onclick = function () {
        console.log(this.id)
    }
    xy$("bx2").onclick = function () {
        console.log(this.id)
    }
    xy$("bx3").onclick = function () {
        console.log(this.id)
    }
</script>
</body>
</html>

點擊bx3 ,bx1和bx2 都有效果
在這裏插入圖片描述

阻止事件冒泡

阻止事件冒泡方法

window.event.cancelBubble=true;//谷歌,IE8支持,火狐不支持
e.stopPropagation();//谷歌和火狐支持

window.event和e都是事件參數對象,一個是IE的標準,一個是火狐的標準
事件參數e在IE8的瀏覽器中是不存在,此時用window.event來代替

上面的例子就可以變成這樣:爲了省變篇幅只寫JS部分

   //阻止事件冒泡函數
    function stopBubble(e) {
        if (e && e.stopPropagation)
            e.stopPropagation()
        else
            window.event.cancelBubble = true
    }

    var xy$ = function (id) {
        return document.getElementById(id)
    };
    xy$("bx1").onclick = function () {
        console.log(this.id)
    };
    xy$("bx2").onclick = function () {
        console.log(this.id)
    };
    xy$("bx3").onclick = function (e) {
        console.log(this.id);
        stopBubble(e)
    }

效果
在這裏插入圖片描述

事件階段

1.事件捕獲階段:從外到內
2.事件目標階段:選擇的那個
3.事件冒泡階段:從內到外

通過e.eventPhase這個屬性返回事件傳播的當前階段
* 如果這個屬性的值是:
* 1---->捕獲階段
* 2---->目標階段
* 3---->冒泡
*

 	
    var xy$ = function (id) {
        return document.getElementById(id)
    };
    var objs = [xy$("bx3"), xy$("bx2"), xy$("bx1")];
    //遍歷註冊事件
    objs.forEach(function (ele) {
        //爲每個元素綁定事件
        ele.addEventListener("click", function (e) {
            console.log(this.id + ":" + e.eventPhase);
        }, false);
    });


在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章