1
头图

Clicking, scrolling, touching, dragging...These means for users to web page can be called "events". Understanding JavaScript , whether it is for optimizing some user interactions or processing online BUG will be very useful. Great help.

Closer to home, the "events" triggered by the user during the interaction can be divided into the following stages👇

  • Capture phase: the event is window object, from top to bottom to the target object
  • Target stage: the event is triggered on the target object
  • Bubbling stage: the event starts from the target object, first acts on the target object itself, from bottom to top to the outermost HTML element

1619844531934.jpg

How to enable bubbling & capture? ?

The triggering phase of the event has been mentioned above, so how to use bubbling & capture in the actual encoding process? In fact, addEventListener provides bubbling events by default. Assuming you want to enable capture, you can directly set it like this:

// 代码仅供参考
const el = document.querySelector('div');
el.addEventListener('click', function(e) {
    console.log('test');
}, true)

Of course addEventListener also provides a more detailed optional configuration👇

addEventListener.png

Step on the pit

Next we look at a demo 👇

HTML code 👇

<div class="container">
    <div class="content">
        <!-- 足够使 content 这个 div 出现滚动条的文本 -->
    </div>
</div>

JavaScript code 👇

const el = document.querySelector('container');
el.addEventListener('scroll', function(e){
    console.log('scroll');
});

After running you will find that in any case the rolling content in the text, are not log printed, then content rolling when there's no bubble? ! !

In fact, there are indeed some events without the "bubbling phase". The scroll event is one of them. The "bubbling phase" can document or window , otherwise only the "capture phase" can be used.

If you MDN , you will find that this is not mentioned, and it is also emphasized that the scroll event can bubble 👇

image.png

Instead, it prompts that there is a bubbling stage, but if you switch to the traditional Chinese version, it will be embarrassing😅

image.png

To the effect: no bubbling on the element, but bubbling on document and window .

Note that the default view mentioned here is actually document.defaultView , and the return value is Window .

In other words, for the scroll event, its bubbling occurs from document to window objects.

to sum up

  • After the event occurs, there are generally three phases, namely the "capture phase", the "target object" phase, and the "bubbling phase". But not all events necessarily have a "bubbling phase", such as scroll events or other media types of events
  • MDN document is not very accurate. It is best to compare the differences between different language versions when searching for the document (also related to the person who translated the document, which may contain private goods 😄)

reference

Bubbling and capturing

scroll


tonychen
1.2k 声望272 粉丝