.hover()


將一個或兩個處理常式繫結到匹配的元素,在滑鼠指標進入和離開元素時執行。

.hover( handlerIn, handlerOut )傳回:jQuery已棄用版本:3.3

說明:將兩個處理常式繫結到匹配的元素,在滑鼠指標進入和離開元素時執行。

此 API 已棄用。改用 .on( "mouseenter", handlerIn ).on( "mouseleave", handlerOut )

.hover() 方法會繫結 mouseentermouseleave 事件的處理常式。您可以使用它來在滑鼠游標位於元素內時,對元素套用行為。

呼叫 $( selector ).hover( handlerIn, handlerOut ) 等同於

1
$( selector ).on( "mouseenter", handlerIn ).on( "mouseleave", handlerOut );

請參閱 mouseentermouseleave 的討論,以取得更多詳細資料。

範例

若要為滑鼠游標懸停其上的清單項目新增特殊樣式,請嘗試

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover demo</title>
<style>
ul {
margin-left: 20px;
color: blue;
}
li {
cursor: default;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<ul>
<li>Milk</li>
<li>Bread</li>
<li class="fade">Chips</li>
<li class="fade">Socks</li>
</ul>
<script>
$( "li" ).hover(
function() {
$( this ).append( $( "<span> ***</span>" ) );
}, function() {
$( this ).find( "span" ).last().remove();
}
);
$( "li.fade" ).hover(function() {
$( this ).fadeOut( 100 );
$( this ).fadeIn( 500 );
});
</script>
</body>
</html>

示範

若要為滑鼠游標懸停其上的表格儲存格新增特殊樣式,請嘗試

1
2
3
4
5
6
7
$( "td" ).hover(
function() {
$( this ).addClass( "hover" );
}, function() {
$( this ).removeClass( "hover" );
}
);

若要取消繫結上述範例,請使用

1
$( "td" ).off( "mouseenter mouseleave" );

.hover( handlerInOut )傳回:jQuery已棄用版本:3.3

說明:繫結單一處理常式至配對的元素,在滑鼠游標進入或離開元素時執行。

此 API 已棄用。改用 .on( "mouseenter mouseleave", handlerInOut )

當傳遞單一函式時,.hover() 方法會為 mouseentermouseleave 事件執行該處理常式。這允許使用者在處理常式中使用 jQuery 的各種切換方法,或根據 event.type 在處理常式中做出不同的回應。

呼叫 $(selector).hover(handlerInOut) 等同於

1
$( selector ).on( "mouseenter mouseleave", handlerInOut );

請參閱 mouseentermouseleave 的討論,以取得更多詳細資料。

範例

滑鼠移到下一個 LI 兄弟元素時,向上或向下滑動,並切換一個類別。

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover demo</title>
<style>
ul {
margin-left: 20px;
color: blue;
}
li {
cursor: default;
}
li.active {
background: black;
color: white;
}
span {
color:red;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<ul>
<li>Milk</li>
<li>White</li>
<li>Carrots</li>
<li>Orange</li>
<li>Broccoli</li>
<li>Green</li>
</ul>
<script>
$( "li" )
.odd()
.hide()
.end()
.even()
.hover(function() {
$( this )
.toggleClass( "active" )
.next()
.stop( true, true )
.slideToggle();
});
</script>
</body>
</html>

示範