我一直使用mouseover
事件,但在阅读jQuery文档时发现了mouseenter
。它们似乎完全相同。
它们是否有区别,如果有,应该在什么情况下使用?
(同样适用于mouseout
与mouseleave
)。
我一直使用mouseover
事件,但在阅读jQuery文档时发现了mouseenter
。它们似乎完全相同。
它们是否有区别,如果有,应该在什么情况下使用?
(同样适用于mouseout
与mouseleave
)。
var i = 0;
$("div.overout")
.mouseover(function() {
i += 1;
$(this).find("span").text("mouse over x " + i);
})
.mouseout(function() {
$(this).find("span").text("mouse out ");
});
var n = 0;
$("div.enterleave")
.mouseenter(function() {
n += 1;
$(this).find("span").text("mouse enter x " + n);
})
.mouseleave(function() {
$(this).find("span").text("mouse leave");
});
div.out {
width: 40%;
height: 120px;
margin: 0 15px;
background-color: #d6edfc;
float: left;
}
div.in {
width: 60%;
height: 60%;
background-color: #fc0;
margin: 10px auto;
}
p {
line-height: 1em;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="out overout">
<span>move your mouse</span>
<div class="in">
</div>
</div>
<div class="out enterleave">
<span>move your mouse</span>
<div class="in">
</div>
</div>
mouseover()
:.mouseover()
]由于事件冒泡可能会引起许多头痛。例如,在此示例中,当鼠标指针移到 Inner 元素上时,将向其发送鼠标悬停事件,然后向外层传递。这可能会在不恰当的时间触发我们绑定的鼠标悬停处理程序。有关实用替代方法,请参见 .mouseenter()
的讨论。”Mouseenter和mouseleave不会响应事件冒泡,而mouseover和mouseout会。
这里有一篇文章描述了这种行为。
通常,像这样的问题,Quirksmode有最佳答案。
我想,因为jQuery的一个目标是使事物浏览器无关,使用任何事件名称都会触发相同的行为。编辑:感谢其他帖子,我现在看到这不是这种情况。
$(document).ready(function() {
$("#outer_mouseover").bind
("Mouse Over Mouse Out",function(event){
console.log(event.type," :: ",this.id);})
$("#outer_mouseenter").bind
("Mouse enter Mouse leave",function(event){
console.log(event.type," :: ",this.id);})
});
mouseenter
事件不是只有在鼠标从父元素移动到该元素时才会触发。该事件会在鼠标从元素外部进入到内部时触发,无论鼠标来自哪个元素。虽然通常鼠标会来自父元素,但并非总是如此。例如,如果父元素没有填充或边框,则鼠标可以直接从祖父元素进入,此时mouseenter
事件仍将触发。实际上,它甚至可以从视窗外面进入元素(如果该元素恰好位于边缘),并且事件仍会触发。 - callum