当前位置:网站首页>Event capture and bubbling - what is the difference between them?

Event capture and bubbling - what is the difference between them?

2022-07-27 06:54:00 THER1881

Event Bubbling 、 Capture : Event bubbling and event capture were proposed by Microsoft and Netscape respectively , Both of these concepts are designed to solve the problem of event flow in a page ( Sequence of events ) The problem of .

1、 Event Bubbling

Microsoft came up with an event stream called event bubble . Structurally ( Not visually ) Elements of nested relationships , There will be bubble function , The same thing , Bubbling from child to parent .( Bottom up )

Then let's verify it :

<style>
    *{
    
        margin: 0;
        padding: 0;
    }
    div{
    
        width: 200px;
        height: 100px;
        background-color: red;
        text-align: center;
        line-height: 100px;
        cursor: pointer;
    }
</style>
<body>
    <div> Click on </div>
    <script>
        let body = document.querySelector('body')
        let div = document.querySelector('div')
        body.addEventListener('click',function(){
    
            console.log('body')
        })
        div.addEventListener('click',function(){
    
            console.log('1')
        })
    </script>
</body>

 Insert picture description here

2、 Event capture

Structurally ( Not visually ) Elements of nested relationships , There will be event capture capabilities , The same thing , From parent to child ( Event source element ).( The top-down )(ie No capture events )

Then let's verify it :

<style>
    *{
    
        margin: 0;
        padding: 0;
    }
    div{
    
        width: 200px;
        height: 100px;
        background-color: red;
        text-align: center;
        line-height: 100px;
        cursor: pointer;
    }
</style>
<body>
    <div> Click on </div>
    <script>
        let body = document.querySelector('body')
        let div = document.querySelector('div')
        body.addEventListener('click',function(){
    
            console.log('body')
        },ture)
        div.addEventListener('click',function(){
    
            console.log('1')
        },ture)
    </script>
</body>

 Insert picture description here

difference

Event Bubbling : One from the inside out , Bubbling , Extend to the upper level .

Event capture : One from the outside to the inside , Go to capture , Form a downward trend .

原网站

版权声明
本文为[THER1881]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207270520474270.html