The event fires only if the mouse pointer is outside the boundaries of the object and the user moves the mouse pointer inside the boundaries of the object. If the mouse pointer is currently inside the boundaries of the object, for the event to fire, the user must move the mouse pointer outside the boundaries of the object and then back inside the boundaries of the object.
let contains = docEle.contains ? function (parent, node) {
return parent !== node && parent.contains(node)
} : function (parent, node) {
let result = parent !== node
if (!result) { // 排除parent与node传入相同的节点
return result
}
if (result) {
while (node && (node = node.parentNode)) {
if (parent === node) {
return true
}
}
}
return false
}
说了这么多,我们来看看用 mouseover 事件模拟 mouseenter 的最终代码
// callback表示如果执行mouseenter事件时传入的回调函数
let emulateEnterOrLeave = function (callback) {
return function (e) {
let relatedTarget = e.relatedTarget
if (relatedTarget !== this && !contains(this, relatedTarget)) {
callback.apply(this, arguments)
}
}
}
// callback表示如果执行mouseenter事件时传入的回调函数
let emulateEnterOrLeave = function (callback) {
return function (e) {
let relatedTarget = e.relatedTarget
if (relatedTarget !== this && !contains(this, relatedTarget)) {
callback.apply(this, arguments)
}
}
}