How do I handle a click anywhere in the page, even when a certain element stops the propagation?

后端 未结 8 1792
臣服心动
臣服心动 2020-12-04 23:51

We are working on a JavaScript tool that has older code in it, so we cannot re-write the whole tool.

Now, a menu was added position fixed to the bottom and the clien

8条回答
  •  攒了一身酷
    2020-12-05 00:11

    Events in modern DOM implementations have two phases, capturing and bubbling. The capturing phase is the first phase, flowing from the defaultView of the document to the event target, followed by the bubbling phase, flowing from the event target back to the defaultView. For more information, see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow.

    To handle the capturing phase of an event, you need to set the third argument for addEventListener to true:

    document.body.addEventListener('click', fn, true); 
    

    Sadly, as Wesley mentioned, the capturing phase of an event cannot be handled reliably, or at all, in older browsers.

    One possible solution is to handle the mouseup event instead, since event order for clicks is:

    1. mousedown
    2. mouseup
    3. click

    If you can be sure you have no handlers cancelling the mouseup event, then this is one way (and, arguably, a better way) to go. Another thing to note is that many, if not most (if not all), UI menus disappear on mouse down.

提交回复
热议问题