问题
What is the difference between jQuery\'s mouseout() and mouseleave()?
回答1:
The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.
Source: http://api.jquery.com/mouseleave/
回答2:
There can be times when mouseout
is a better choice than mouseleave
.
For example, let's say you've created a tooltip that you want displayed next to an element on mouseenter
. You use setTimeout
to prevent the tooltip from popping up instantly. You clear the timeout on mouseleave
using clearTimeout
so if the mouse leaves the tooltip won't be displayed. This will work 99% of the time.
But now let's say the element you have a tooltip attached to is a button with a click
event, and let's also assume this button prompts the user with either a confirm
or alert
box. The user clicks the button and the alert
fires. The user pressed it fast enough that your tooltip didn't have a chance to pop up (so far so good).
The user presses the alert
box OK button, and the mouse leaves the element. But since the browser page is now in a locked state, no javascript will fire until the OK button has been pressed, meaning your mouseleave
event WILL NOT FIRE. After the user presses OK the tooltip will popup (which is not what you wanted).
Using mouseout
in this case would be the appropriate solution because it will fire.
回答3:
jQuery API doc:
mouseout
This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times. See the discussion for .mouseleave() for a useful alternative.
So mouseleave
is a custom event, which was designed because of the above reason.
http://api.jquery.com/mouseleave/
回答4:
Event Mouseout will trigger when mouse leaves the selected element and also when mouse leaves it's child elements also.
Event Mouseleave element will trigger when pointer will leave the selected element only.
Reference: W3School
来源:https://stackoverflow.com/questions/4258615/what-is-the-difference-between-jquerys-mouseout-and-mouseleave