.mouseout()

.mouseout( handler )返回类型:jQuery

描述:把一个事件处理函数绑定到“mouseout”JavaScript事件,或者在元素上触发此事件。

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

当鼠标指针移出某元素时,mouseout鼠标发送到该元素。任何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" ).mouseout(function() {
$( "#log" ).append( "Handler for .mouseout() called." );
});

现在当鼠标指针移出Outer <div>时,消息追加到<div id="log">后面。若要手工触发此事件,请不带参数地应用.mouseout()

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

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

因为事件冒泡,此事件可能导致很多令人头痛的问题。例如,在此示例中,当鼠标指针移出Inner元素时,也将发送mouseout事件,然后冒泡到Outer元素。这可能会不合时宜地触发绑定的mouseout处理函数。请参阅对.mouseleave()的讨论以获得有用的替代方案。

补充说明:

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

示例:

显示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
65
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mouseout 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" )
.mouseout(function() {
$( "p:first", this ).text( "mouse out" );
$( "p:last", this ).text( ++i );
})
.mouseover(function() {
$( "p:first", this ).text( "mouse over" );
});
var n = 0;
$( "div.enterleave" )
.on( "mouseenter", function() {
$( "p:first", this ).text( "mouse enter" );
})
.on( "mouseleave", function() {
$( "p:first", this ).text( "mouse leave" );
$( "p:last", this ).text( ++n );
});
</script>
</body>
</html>

演示: