塩漬け魚のフロントエンドの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はどちらもイベントパラメータオブジェクトで、1つはIEの標準で、もう1つはFirefoxの標準です。
イベントパラメータeはIE8ブラウザには存在しません。

上記の例は次のようになる可能性があります:スペースを節約するために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);
    });


ここに画像の説明を挿入

166の元の記事を公開 22の賞賛 10,000以上のビュー

おすすめ

転載: blog.csdn.net/weixin_45020839/article/details/105030692