1. 程式人生 > 程式設計 >淺析js中事件冒泡與事件捕獲

淺析js中事件冒泡與事件捕獲

目錄
  • 01-事件冒泡
    • 1.1-事件冒泡介紹
    • 1.2-事件冒泡利用(事件委託)
    • 1.3-事件冒泡影響 與 阻止事件冒泡
  • 02-事件捕獲
    • 1.1-事件捕獲介紹
    • 1.2-事件三個階段

01-事件冒泡

1.1-事件冒泡介紹

本小節知識點:介紹什麼是事件冒泡

  • 事件冒泡:如果一個元素的事件被觸發,那麼他的所有父級元素的同名事件也會被依次觸發

元素->父元素->body->html->document->window

事件冒泡一直存在,只不過以前我們沒有給父級元素加同名事件

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>事件冒泡</title>
    <style>
        .parent {
            position: relative;

            width: 200px;
            height: 200px;
            background-color: pink;
        }

        .son {
            position: absolute;

            left: 400px;
            top: 300px;

            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>

<body>
    <!-- 冒泡: bubble -->

    <div class="parent">
        <div class="son"></div>
    </div>

    <script>
        // 證明冒泡: 給父子新增同類型事件即可

        const parent = document.querySelector('.parent')
        const son = parent.firstElementChild

        // 給父子繫結點選事件
        parent.onclick = function () {
            console.log('parent')
        }

        // 點選parent元素: 輸出parent, 點選son元素: 也輸出parent
        // 1. 事件是所有元素都有的: 給不給事件, 都有
        // 2. 點選son觸發了parent的點選事件: 事件冒泡發生

        // 所有元素都有事件, 包括頂級物件window
        window.onclick = function () {
            console.log('windwww.cppcns.com
ow') } // 事件鏈條: 目標元素-》上級-》上級-》body-》html-》document-》window // 事件冒泡: 大部分的時候沒用(還有壞處) </script> </body> </html>

1.2-事件冒泡利用(事件委託)

本小節知識點:介紹事件冒泡的好處

​ 事件冒泡好處:如果想給父元素的多個子元素新增事件,我們可以只需要給父元素新增事件即可,然後

通過獲取事件源(e.target)就可以得知是哪一個子元素觸發了這個事件

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>事件冒泡 - 應用 - 事件委託</title>
    <style>
        li {
            margin: 20px 0;
        }
    </style>
</head>

<body>
    <ul>
        <li>百里守約1</li>
        <li>百里守約2</li>
        <li>百里守約3</li>
    </ul>

    <script>
        // 需求: 給所有li增加滑鼠的移入移出事件: 變色即可
        // document.querySelectorAll('li').forEach(function (li) {
        //     li.onmouseover = function () {
        //         this.style.backgroundColor = 'red'
        //     }

        //     li.onmouseout = function () {
        //         this.style.backgroundColor = ''
        //     }
        // })

        // 1. 程式碼的執行效率偏低: 需要給所有的li,一個一個的繫結事件
        // 2. 可擴充套件性弱: 新增一個li,將會無效
        // innerHTML: 所有都無效
        // document.querySelector('ul').innerHTML += '<li>innerHTML的li</li>'
        // 邏輯: 取出ul中的所有li(結構,不包含事件),再放進去(字串形式): 所有的事件全部丟失

        // document.createElement() + appendChild(): 新增的無效
        // let li = document.createElement('li')
        // li.innerHTML = 'creatElement建立的li'
        // document.querySelector('ul').appendChild(li)

        // 事件委託: 將子元素該繫結的事件(效果程式碼) 繫結到父元素身上
        document.querySelector('ul').onmouseover = function (e) {
            // 事件物件中: e.target 是觸發事件的原始目標(最上面的孩子)
            console.log(e.target)

            // 如何區分目標元素是li還是ul呢? 節點: 節點三要素
            // nodeType: li和ul都是元素,1
            // nodeValue: li和元素都是元素,null
            // nodeName: 是元素標籤名字的大寫: LI UL
            console.log(e.target.nodeName)
            if (e.target.nodeName === 'LI') {
                // 是目標元素
                e.target.style.backgroundColor = 'red'
            }
        }

        document.querySelector('ul').onxJtNhUbC
mouseout = function (e) { if (e.target.nodeName === 'LI') { // 是目標元素 e.target.style.backgroundColor = '' } } // 最大的優點: 事件繫結一次(效能極大提升) // 次要優點: 不論是innerHTMl的修改還是createElement的建立: 所有的li都有效 // document.querySelector('ul').innerHTML += '<li>innerHTML的li</li>' // 正是因為有了事件委託: 以後不用再使用建立元素,直接使用innerHTML方便太多 // let li = document.createElement('li') // li.innerHTML = 'creatElement建立的li' // document.querySelector('ul').appendChild(li) http://www.cppcns.com
// 事件委託: 是事件冒泡唯一的價值(挺有用) </script> </body> </html>

1.3-事件冒泡影響 與 阻止事件冒泡

  • 本小節知識點:介紹事件冒泡的影響

事件冒泡會導致需求衝突:例如我想要新增一個功能,彈出登入窗之後點選body空白區域讓登陸窗消失
此時a標籤彈出登入窗的點選事件會觸發body的點選事件,導致登陸窗一出來就消失

解決方案:阻止事件冒泡(下一小節知識點)

  • 本小節知識點:阻止事件冒泡

阻止事件冒泡:讓同名事件不要在父元素中冒泡(觸發)

 * 說人話:點選一個元素只會觸發當前元素的事件,不會觸發父元素的同名事件

語法: 事件物件.stopPropagation() IE8及之前不支援

事件物件.cancelBubble = true IE8之前支援

注意:如果想要阻止事件冒泡,一定要在觸發事件的函式中接收事件物件

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>事件冒泡 - 影響 - 阻止事件冒泡</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        a {
            text-decoration: none;
            display: block;

            width: 200px;
            margin: 20px auto;
        }

        .form {
            position: relative;

            width: 400px;
            height: 200px;
            margin: 0 auto;
            text-align: center;
            border: 1px solid #ccc;

            display: none;
        }

        .form span {
            display: block;
            position: absolute;
            right: -25px;
            top: -25px;

            width: 50px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            border: 1px solid #ccc;
            border-radius: 50%;
            background-color: #fff;
            cursor: pointer;

        }
    </style>
</head>

<body>
    <a href=":;" rel="external nofollow" >點我顯示登入框</a>

    <div class="form">
        <span>X</span>
        使用者名稱: <input type="text" name="username"><br>
        密碼: <input type="password" name="password"><br>
        <button>登入</button>
    </div>

    <script>
        // 事件冒泡: 子元素事件觸發,導致父元素相同事件被觸發

        // 需求: 點選 連結 顯示登入框,點選任何空白地方,都要隱藏登入框
        const a = document.querySelector('a')
        const form = document.querySelector('.form')
        const x = form.firstElementChild

        // 阻止冒泡: 阻止事件的傳遞: 事件物件e.stopPropagation()
        // 子元素如果不希望父元素觸發子元素相同的事件: 在子元素的事件中,阻止傳遞

        // 1. 給a做點選事件: 顯示div.form
        a.onclick = function (e) {
            console.log('a')
            form.style.display = 'block'

            console.log(e)
            // 阻止傳遞: 點選事件,到a這裡結束
            e.stopPropagation()
        }

        // 2. 點選空白隱藏div.form: 簡單: 給document || window做點選事件
        document.onclick = function () {
            console.log('document')
            form.style.display = ''
    xJtNhUbC    }

        // 3. 為了安全: 讓整個formdiv都可以點選,不會傳遞
        form.onclick = function (e) {
            e.stopPropagation()
        }

        // 4. 點選關閉
        x.onclick = function () {
            form.style.display = ''
        }

        // 總結
        // 實際開發中: 可能會出現父子出現相同型別的事件,如果效果相反(a要顯示div,document要隱藏div),一般會用到阻止事件傳遞: e.stopPropagation()
    </script>
</body>

</html>

02-事件捕獲

1.1-事件捕獲介紹

本小節知識點:事件捕獲

  • 1.事件冒泡:從觸發事件元素,一級一級往上找父元素觸發同名事件,如果有就觸發
  • 2.事件捕獲:從最頂級的父元素一級一級往下找子元素觸發同名事件,直到觸發事件的元素為止

事件捕獲與事件冒泡觸發事件的順序完全相反

  • 3.事件捕獲,只能通過addEventListener並且引數寫true才是事件捕獲

其他都是冒泡(不是通過addEventListener新增、addEventListener引數為false)

  • 4.事件物件.stopPropagation() 除了可以阻止冒泡還可以阻止捕獲
  • 5.IE8及以前沒有捕獲!

1.2-事件三個階段

本小節知識點:介紹事件的三個階段

  • 1.事件一共有三個階段:事件的執行順序

1–捕獲階段 :
2–目標階段 :
3–冒泡階段 :

  • 2.事件物件.eventPhase 可以獲得觸發這個事件時,到底是哪個階段
  • 3.先從最頂級往下一級一級捕獲,然後到目標的捕獲,目標的冒泡,再一級一級往上冒泡
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>事件捕獲</title>
</head>

<body>
    <div class="box">我是小馬哥</div>

    <script>
        // on事件: 全部都是冒泡事件

        window.onclick = function () {
            console.log('window的冒泡事件')
        }

        document.onclick = function () {
            console.log('document的冒泡事件')
        }

        const box = document.querySelector('.box')

        box.onclick = function () {
            console.log('box的冒泡事件')
        }

        // 捕獲事件:只有一種方式 addEventListener('事件型別',回撥函式,true)
        window.addEventListener('click',function () {
            // console.log('window的捕獲事件')
        },true)

        document.addEventListener('click',function () {
            console.log('document的捕獲事件')
        },true)

        // 事件捕獲的唯一價值: 給事件目標做準備

        // 事件流: 先捕獲  後目標  再冒泡
        // 目標階段: 不區分捕獲還是冒泡(哪個程式碼在前面,哪個先執行)
        // 最新的谷歌: 先捕獲後冒泡
        // IE是按順序(目標階段)

        // box前面已經有點選冒泡
        box.addEventListener('click',function () {
            console.log('box的捕獲事件')
        },true)

        // e.stopPropagation() 組織事件傳遞: 如果在捕獲階段阻止: 導致出bug
        window.addEventListener('click',function (e) {
            e.stopPropagation()
        },true)

    </script>
</body>

</html>```

到此這篇關於淺析js中事件冒泡與事件捕獲的文章就介紹到這了,更多相關js事件冒泡與事件捕獲內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!