mouseover和mouseenter事件有什么区别?

时间:2009-07-09 14:45:16

标签: javascript jquery events javascript-events

我一直使用mouseover事件,但在阅读jQuery文档时,我发现mouseenter。它们似乎完全相同。

两者之间是否存在差异?如果是,我应该何时使用它们? (也适用于mouseout vs mouseleave)。

4 个答案:

答案 0 :(得分:110)

您可以在the jQuery doc页面中试用以下示例。这是一个很好的小型互动演示,它非常清晰,你可以亲自看看。

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>

简而言之,您会注意到当一个元素在它上面时会发生一个鼠标悬停事件 - 来自它的子OR或父元素,但只有当鼠标从该元素外部移动到鼠标时才会发生鼠标输入事件这个元素。

as the mouseover() docs说出来:

  

[.mouseover()]会因事件冒泡而导致许多麻烦。例如,当鼠标指针在此示例中移动到Inner元素上时,鼠标悬停事件将被发送到该元素,然后逐渐渗透到外部。这可以在不合适的时间触发我们的绑定鼠标悬停处理程序。有关有用的替代方案,请参阅.mouseenter()的讨论。

答案 1 :(得分:41)

Mouseenter和mouseleave 对事件冒泡做出反应,而鼠标悬停和mouseout 执行

这是描述行为的article

答案 2 :(得分:4)

对于像这样的问题通常都是如此,Quirksmode有the best answer

我想,因为jQuery的目标之一是使浏览器不可知,使用任一事件名称都会触发相同的行为。编辑:感谢其他帖子,我现在看到这是不是这样的

答案 3 :(得分:0)

$(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);})
 });

相关问题