I have always used the mouseover event, but while reading the jQuery documentation I found mouseenter. They seem to function exactly the same.

这两者之间有区别吗?如果有,我应该什么时候使用它们?
(也适用于mouseoutmouseleave).

推荐答案

你可以在the jQuery doc页中try 下面的例子.这是一个很好的互动演示,非常清晰,你可以自己看.

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>

简而言之,您会注意到,当您在某个元素上移动时,该元素上会发生鼠标悬停事件(来自其子元素或父元素),但只有当鼠标从该元素外部移动到此元素时,才会发生鼠标悬停事件.

或者as the mouseover() docs个人说:

[.mouseover()]由于事件冒泡,可能会导致许多头痛.例如,在本例中,当鼠标指针移动到内部元素上时,一个mouseover事件将被发送到该元素,然后向上滴到外部元素.这可能会在不合适的时候触发绑定的鼠标悬停处理程序.有关有用的替代方案,请参见.mouseenter()的讨论.

Jquery相关问答推荐

当我使用 OwlCarousel 时,没有任何显示

如何在光滑的轮播上添加进度条

添加动态表单后,Select2 消失

在 Mastodon 中将 jQuery 添加到 Rails 6

jQuery:在mousemove事件期间检测按下的鼠标按钮

为什么在 jQuery 插件中返回 this.each(function())?

与其他 Javascript 框架相比,为什么 jQuery 被如此广泛地采用?

缺少 .map 资源?

禁用提交按钮,直到所有字段都有值

如何获取将在不提交的情况下提交的所有表单值

用按钮切换显示/隐藏div?

如何在不导致页面滚动的情况下删除位置哈希?

使用 JQuery 更改 :before css Select 器的宽度属性

如何获取文档的滚动位置?

jQuery ajax 成功回调函数定义

你如何记录jQuery中一个元素触发的所有事件?

如何在jQuery中 Select 最后一个子元素?

添加到数组 jQuery

如何使用 jQuery Select 第一个父 DIV?

JS - 从base64代码中获取图片的宽高