[英]What's the difference between mouseenter and mouseover, and mouseout and mouseleave?
[英]What is the difference between the mouseover and mouseenter events?
我一直使用mouseover
事件,但在阅读 jQuery 文档时我发现了mouseenter
。 他们好像和function一模一样。
两者之间有区别吗?如果有,我应该什么时候使用它们?
(也适用于mouseout
与mouseleave
)。
您可以从jQuery 文档页面尝试以下示例。 这是一个不错的小型交互式演示,它非常清晰,您实际上可以亲眼看到。
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()
] 会由于事件冒泡而引起许多麻烦。 例如,在此示例中,当鼠标指针移到内部元素上时,鼠标悬停事件将发送到该元素,然后向上移动到外部元素。 这可能会在不合时宜的时候触发我们绑定的鼠标悬停处理程序。 请参阅.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);})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.