JavaScript事件處理機制(捕獲,目標,冒泡)

事件處理機制的三個階段(捕獲階段,目標階段,冒泡階段)

   

冒泡階段:事件從內向外執行捕獲階段:事件從外向內執行;     

 

  1. addEventListener(type,fn,useCapture)
  2. useCapture:事件處理機制(捕獲階段true,目標階段,冒泡階段false)默認爲冒泡階段
  3. 捕獲階段:事件從外向內執行; 冒泡階段:事件從內向外執行

捕獲情況:

    <style>
        #parent{
            height: 300px;
            width: 300px;
            background-color: red;
        }
        #son{
            height: 100px;
            width: 100px;
            background-color: green;
        }
    </style>
</head>
<body>
    <div id="parent">
        <div id="son"></div>
    </div>
</body>
<script>
    document.getElementById('parent').addEventListener('click',function(e){
        console.log('是你爸爸')
    },true)
    document.getElementById('son').addEventListener('click',function(e){
        console.log('你兒子')
    },true)
</script>


冒泡情況:

    <style>
        #parent{
            height: 300px;
            width: 300px;
            background-color: red;
        }
        #son{
            height: 100px;
            width: 100px;
            background-color: green;
        }
    </style>
</head>
<body>
    <div id="parent">
        <div id="son"></div>
    </div>
</body>
<script>
    document.getElementById('parent').addEventListener('click',function(e){
        console.log('是你爸爸')
    },false)
    document.getElementById('son').addEventListener('click',function(e){
        console.log('你兒子')
    },false)
</script>


阻止冒泡行爲:

    <style>
        #parent{
            height: 300px;
            width: 300px;
            background-color: red;
        }
        #son{
            height: 100px;
            width: 100px;
            background-color: green;
        }
    </style>
</head>
<body>
    <div id="parent">
        <div id="son"></div>
    </div>
</body>
<script>
    document.getElementById('parent').addEventListener('click',function(e){
        console.log('是你爸爸')
    },false)
    document.getElementById('son').addEventListener('click',function(e){
        console.log('你兒子')
        e.stopPropagation() // 阻止冒泡
    },false)
</script>

阻止冒泡行爲的兼容性:

非 IE8及以下瀏覽器 使用 e.stopPropagation()

IE8及以下瀏覽器 使用 window.event.cancelBubble = true

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