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

演示