I have always used the mouseover
event, but while reading the jQuery documentation I found mouseenter
. They seem to function exactly the same.
这两者之间有区别吗?如果有,我应该什么时候使用它们?
(也适用于mouseout
对mouseleave
).
I have always used the mouseover
event, but while reading the jQuery documentation I found mouseenter
. They seem to function exactly the same.
这两者之间有区别吗?如果有,我应该什么时候使用它们?
(也适用于mouseout
对mouseleave
).
你可以在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()
的讨论.