不知道大家在面试或者工作过程中有没有被 mouseover
和 mouseenter
(对应的是 mouseout
和 mouseleave
)事件所困扰。自己之前在面试的时候就有被问到诸如mouseover和mouseenter事件的异同之类的问题?当时没有答出来,一直也对这两个事件有点模糊不清,趁着最近正在读 zepto源码 ,准备写一篇这方面的文章,如果有错误,请大家指正。
mouseenter与mouseover的异同?
要说清楚mouseenter与mouseover有什么不同,也许可以从两方面去讲。
是否支持冒泡 事件的触发时机
先来看一张图,对这两个事件有一个简单直观的感受。
再看看官网对mouseenter的解释
mouseenter | onmouseenter event
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.
大概意思是说:当鼠标从元素的边界之外移入元素的边界之内时,事件被触发。而当鼠标本身在元素边界内时,要触发该事件,必须先将鼠标移出元素边界外,再次移入才能触发。(英语比较渣:no_mouth:,凑合看哈)
Unlike the onmouseover event, the onmouseenter event does not bubble.
大概意思是:和mouseover不同的是,mouseenter不支持事件冒泡 (英语比较渣:no_mouth:,凑合看哈)
由于mouseenter不支持事件冒泡,导致在一个元素的子元素上进入或离开的时候会触发其mouseover和mouseout事件,但是却不会触发mouseenter和mouseleave事件
我们用一张动图来看看他们的区别(或者点击该链接体验)。
我们给左右两边的ul分别添加了 mouseover
和 mouseenter
事件,当鼠标进入左右两边的ul时, mouseover
和 mouseenter
事件都触发了,但是当移入各自的子元素li的时候,触发了左边ul上的mouseover事件,然而右边ul的mouseenter事件没有被触发。
造成以上现象本质上是 mouseenter
事件不支持冒泡所致。
摘自:javascript中mouseenter与mouseover的异同
以下为原创:
鼠标悬停显示子元素div层,移到子元素div层该层不消失
div2是div1的子层,鼠标悬停在div1上,div2由隐藏变为显示,鼠标移动到div2,div2不会消失。使用mouseover可以让悬停div1时显示div2。但是怎么在鼠标移到了div2,div2继续存在呢。然后鼠标从div1或者div2移走时,div2消失
解决方法:改mouseover为mouseenter
$("#divSheetlist").on("mouseenter","li", function(event) {
$("#divSheetlist").css("overflow-y","visible");
if($(this).find("#tip").length==0){
var text = '<div id="tip" style="background-color:rgb(168, 211, 254);right:-37px;top:0px;width:37px;height:37px;display:block;;padding: 0px;z-index:999999;margin: 0px 0px 0px 0px; position: absolute;"><img id="img" style="margin-top:3px;margin-left:3px;" src="../../../abacus/_res_/img/hxfx.png" height="30px" width="30px"/><input type="hidden" /></div>';
$(this).append(text);
}
});
$("#divSheetlist").on("mouseleave","li", function(event) {
$(this).children("#tip").remove();
});