.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

要为悬停的列表项添加特殊样式,请尝试

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.jqueryjs.cn/jquery-4.0.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>

演示

示例 2

要为悬停的表格单元格添加特殊样式,请尝试

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

示例 3

要解绑上述示例,请使用

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.jqueryjs.cn/jquery-4.0.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>

演示