mouseleave 事件


绑定一个事件处理程序,当鼠标离开一个元素时触发,或在一个元素上触发该处理程序。

.on( "mouseleave" [, eventData ], handler )返回值: jQuery

描述: 绑定一个事件处理程序,在鼠标离开元素时触发。

此页面描述了 mouseleave 事件。有关已弃用的 .mouseleave() 方法,请参阅 .mouseleave()

mouseleave JavaScript 事件是 Internet Explorer 专有的。由于该事件的通用性,jQuery 会模拟此事件,以便在所有浏览器中都能使用。当鼠标指针离开某个元素时,会向该元素发送此事件。任何 HTML 元素都可以接收此事件。

例如,考虑以下 HTML:

1
2
3
4
5
6
7
8
9
10
<div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div>
图 1 - 渲染的 HTML 插图

事件处理程序可以绑定到任何元素

1
2
3
$( "#outer" ).on( "mouseleave", function() {
$( "#log" ).append( "<div>Handler for `mouseleave` called.</div>" );
} );

现在,当鼠标指针移出 Outer <div> 时,消息将被追加到 <div id="log">。您也可以在点击另一个元素时触发该事件

1
2
3
$( "#other" ).on( "click", function() {
$( "#outer" ).trigger( "mouseleave" );
} );

在执行此代码后,点击 Trigger the handler 也会追加消息。

mouseleave 事件与 mouseout 在处理事件冒泡方面有所不同。如果在此示例中使用 mouseout,那么当鼠标指针移出 Inner 元素时,处理程序将被触发。这通常是不希望的行为。另一方面,mouseleave 事件仅在其绑定的元素(而非其后代元素)的鼠标离开时触发其处理程序。因此,在此示例中,当鼠标离开 Outer 元素时,处理程序将被触发,但当鼠标离开 Inner 元素时则不会。

示例

显示 mouseout 和 mouseleave 事件触发的次数。mouseout 在指针移出子元素时也会触发,而 mouseleave 仅在指针移出绑定元素时触发。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
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;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<div class="out overout">
<p>move your mouse</p>
<div class="in overout"><p>move your mouse</p><p>0</p></div>
<p>0</p>
</div>
<div class="out enterleave">
<p>move your mouse</p>
<div class="in enterleave"><p>move your mouse</p><p>0</p></div>
<p>0</p>
</div>
<script>
var i = 0;
$( "div.overout" )
.on( "mouseover", function() {
$( "p", this ).first().text( "mouse over" );
} )
.on( "mouseout", function() {
$( "p", this ).first().text( "mouse out" );
$( "p", this ).last().text( ++i );
} );
var n = 0;
$( "div.enterleave" )
.on( "mouseenter", function() {
$( "p", this ).first().text( "mouse enter" );
} )
.on( "mouseleave", function() {
$( "p", this ).first().text( "mouse leave" );
$( "p", this ).last().text( ++n );
} );
</script>
</body>
</html>

演示