1. 程式人生 > >JavaScript中冒泡與事件委託

JavaScript中冒泡與事件委託

冒泡

事件觸發後事件流的三個階段按順序依次是:

    1、捕獲階段   

    2、目標階段   

    3、冒泡階段

 

大盒子包裹小盒子,兩個盒子都分別新增點選事件,當點選小盒子,兩個盒子的事件都會觸發。

 

事件委託

下級元素委託上級元素,將子孫元素的事件註冊委託給父級元素來代理:

    1、給父元素註冊點選事件

    2、在事件函式中通過( 事件物件.target )獲取最先觸發的元素( 這就是需要被操作的子元素 )

    3、通過 nodeName 檢測是點選了子元素還是點到了父元素上

 

事件物件的  公共屬性方法

屬性:

    事件物件.target  → →  獲取最先觸發的元素

方法:

    事件物件.preventDefault() ; 阻止預設行為( 有相容性 )

    事件物件.stopPropagation() ; 停止冒泡

 

重點

1、onmouseover支援冒泡

2、onmouseenter不支援冒泡

 

栗子

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box1 { width: 500px; height: 500px; background: pink; margin:0 auto; overflow
: hidden; } .box2 { width: 400px; height: 350px; background: yellow; margin: 50px auto; overflow: hidden; } .box3 { width: 300px; height: 200px; background: deeppink; margin: 50px auto; } </style> </head> <body> <div class="box1">box1 <div class="box2">box2 <div class="box3">box3 點選裡面的盒子會冒泡到外面的盒子</div> </div> </div> <script> // click事件栗子 var box1 = document.querySelector('.box1'); box1.onclick = function(){ alert('新增在box1上的事件'); } // onmouseover事件栗子 var box1 = document.querySelector('.box1'); box1.onmouseover = function(){ console.log('新增在box1上的事件'); } </script> </body> </html>

 

<!DOCTYPE html>
<html>

<head>
    <style>
        div {
            width: 100px;
            height: 100px;
            margin: 100px auto;
            padding: 30px;
            text-align: center;
            background-color: rgba(255, 192, 203, 0.466);
        }

        p {
            width: 200px;
            height: 40px;
            line-height: 40px;
            background-color: deeppink;
        }
    </style>
</head>

<body>
    <h5>將滑鼠移動到上面兩個方塊上</h5>
    <h5>父元素添加了 onmouseover 事件,子元素未新增,但是當滑鼠滑過子元素,也同樣會觸發事件</h5>
    <div onmouseover="myOverFunction()"><p id="demo"></p>
    </div>
<i>此栗子參考連結:https://blog.csdn.net/u012309349/article/details/50885149</i>

<script> x = 0; function myOverFunction() { document.getElementById("demo").innerHTML = x += 1; } </script> </body> </html>