Simple mouse movement event:
Enter
The mouseover event will be triggered whenever the mouse pointer passes through the selected element or its sub-elements
The mouseenter event will only be triggered when the mouse pointer passes through the selected element
Move out
No matter the mouse pointer leaves the selected element or any child element, the mouseout event will be triggered
The mouseleave event will only be triggered when the mouse pointer leaves the selected element
Let’s observe the problem through a case:
Bind the mouseout event to a nested level, and you will find that the mouseout event is different from what you imagined
Outer child element
Internal child element
0
0
We found a problem with the mouseout event:
1. Unable to prevent bubbling
2. It will also be triggered on internal child elements
The same problem also exists with the mouseover event, so how do we stop bubbling when the stopPropagation method fails?
1. In order to prevent repeated triggering of mouseover and mouseout, an attribute relatedTarget of the event object is used here. This attribute is used to determine the attributes of the related nodes of the target nodes of the mouseover and mouseout events. To put it simply, when the mouseover event is triggered, the relatedTarget attribute represents the node that the mouse just left. When the mouseout event is triggered, it represents the object the mouse moves to. Since MSIE does not support this attribute, it has alternative attributes, namely fromElement and toElement.
2. With this attribute, we can clearly know which object our mouse is moving from and where it is moving. In this way, we can determine whether the associated object is inside the object we want to trigger the event, or whether it is the object itself. Through this judgment, we can reasonably choose whether to really trigger the event.
3. Here we also use a method for checking whether an object is contained in another object, the contains method. MSIE and FireFox provide checking methods respectively, and a function is encapsulated here.
The processing of jQuery is exactly the same
handle: function(event) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !jQuery.contains(target, related))) {
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = fix;
}
return ret;
}
};
});