简体   繁体   中英

How to know if an event is still bubbling?

I have an SVG element with some nested elements. I have attached a mouseout handler to the SVG element. When I press the mouse in the middle of the SVG element and move it out of the SVG element, I get the following list of events:

down
out <path ...>
out <circle r="39.5">
out <circle r="40">
out <circle r="49.5">
out <svg ...>
up

This means the mouse has first left the path, than it has left the three concentric circles and finally it leaves the SVG element. I am just interested in the last event, which affects the element, who has the handler attached. The SVG element gets all the other events, because they bubble to the SVG element.

How can I know, if an event has been bubbled? How can I ignore those events, which do not affect the element, which has the handler attached?

You can use event.target property to see actually which elements was triggered the event.

 $('#myDiv').on('click', function(e) { console.log(e.target.id); }); 
 #myDiv { background-color: red; width: 100px; height: 100px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='myDiv'> <button id='myButton'>Click me</button> </div> 

It seems to be necessary to check, if target is the same as currentTarget . The answer to another question claims, that this can be done with === . So I use now the following condition in my mouseout handler, to skip the situations, when the event is still bubbling:

svg.onmouseout = function (event) {
  if (event.target === event.currentTarget) {
    // Do what needs to be done after the mouse leaves the SVG element.
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM