简体   繁体   中英

Jquery Mouseenter triggering parent elements

I am trying to create a firebug type rollover element selector, but seem to be having problems with the rollover triggering parent elements that contain my target element.

See the following example:

http://jsbin.com/elofe3/edit

There are 3 divs on the page, all with mouseenter/mouseleave listeners, the largest is totally independent of theother two, the second largest is position ontop of the largest but is not contained within it, and the sallest is nested within the second largest, (it's parent). It may be easier to visualise if you look at the source.

If you click preview and roll you mouse over the central div, you will notice that the second largest div also continues to respond to the mouseenter event and remains outlined in red. To fix this, I tried to add $(this).parent().trigger("mouseout"); on each rollover listener.

http://jsbin.com/elofe3/4/edit

But them when your mouse leaves the smallest (pink) div, to the middle (black) div, the middle div does not fire (presumably because mouseenter/mouseover is not being fired as the mouse has never actually left the central div.

I understand that in this situation I could just add $(this).parent().trigger("mouseover"); to the mouseleave listener on each div, but it would'nt work in evey example, (for instance, a div nested within its parent, but is positioned outside of that parent on the page.)

I require some novel solution to this, it needs to work very similarly to the firebug, element selector (the tool that lets you rollover elements on the page (higlighting them) and click to select them and triggering it to show the source for that element).

Any help greatly appreciated.

This is how mouseenter and mouseleave work. But you are mislead, mouseenter is not triggered on the parent element. Instead, mouseleave is not triggered if you hover over descendants. So it is not that the border is added again, but that it is never removed.

Add the event handlers to mouseover and mouseout and prevent the event from bubbling up:

$("div").mouseover(function(e) {
  e.stopPropagation();
  $(this).css("outline", "solid 3px red");     
});

$("div").mouseout(function(e) {
  e.stopPropagation();
  $(this).css("outline", "none");       
});

http://jsbin.com/elofe3/5/edit

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