.mouseleave()

.mouseleave( handler )返回类型:jQuery

描述:绑定一个要在鼠标离开元素时引发的事件处理函数,或者在元素上触发此处理函数。

此方法在前两种变体中是.on('mouseleave', handler)的简写,在第三种变体中是.trigger('mouseleave')的简写。

mouseleaveJavaScript事件是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" ).mouseleave(function() {
$( "#log" ).append( "<div>Handler for .mouseleave() called.</div>" );
});

现在当鼠标指针移出Outer <div>时,消息追加到<div id="log">后面。也可以在点击别的元素时触发此事件。

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

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

mouseleave事件处理事件冒泡的方式不同于mouseout。如果此示例中使用了mouseout,则当鼠标指针移出Inner元素时,将触发处理函数。这通常是不想要的行为。另一方面,mouseleave方法,只在鼠标离开它绑定的元素时才触发它的处理它的处理函数,离开后代元素时不触发。所以在此示例中,当鼠标离开Outer元素时,触发事件处理函数,但是离开Inner元素时不触发。

补充说明:

  • 因为.mouseleave()方法是.on( "mouseleave", handler )的简写,所以可以使用.off( "mouseleave" )来分离。

示例:

当触发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>mouseleave 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.jquery.com/jquery-1.10.2.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" )
.mouseover(function() {
$( "p:first", this ).text( "mouse over" );
})
.mouseout(function() {
$( "p:first", this ).text( "mouse out" );
$( "p:last", this ).text( ++i );
});
var n = 0;
$( "div.enterleave" )
.mouseenter(function() {
$( "p:first", this ).text( "mouse enter" );
})
.mouseleave(function() {
$( "p:first", this ).text( "mouse leave" );
$( "p:last", this ).text( ++n );
});
</script>
</body>
</html>

演示: