.hover()

把一个或多个处理函数绑定到匹配的元素,当鼠标指针进入或离开元素时执行它们。

.hover( handlerIn, handlerOut )返回类型:jQuery

描述:把一个或多个处理函数绑定到匹配的元素,当鼠标指针进入或离开元素时执行它们。

.hover()方法针对mouseenter事件和mouseleave事件绑定了处理函数。你可以使用它在鼠标处于元素内部时简单应用行为。

调用$( selector ).hover( handlerIn, handlerOut )是下面的简写:

1
$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

请参阅针对.mouseenter().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
<!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-1.10.2.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

描述:把一个处理函数绑定到匹配的元素,当鼠标指示进入或离开此元素时执行它。

.hover()方法,当传递一个函数时,将对mouseenter事件和mouseleave事件都执行该处理函数。这允许用户在处理函数内部使用jQuery的各种各样切换方法,或者在处理函数内部作出不同的响应,取决于event.type

调用$(selector).hover(handlerInOut)是下面的简写:

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

请参阅针对.mouseenter().mouseleave()的讨论以进一步了解细节。

示例:

在悬停时将下一个同辈<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-1.10.2.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" )
.filter( ":odd" )
.hide()
.end()
.filter( ":even" )
.hover(function() {
$( this )
.toggleClass( "active" )
.next()
.stop( true, true )
.slideToggle();
});
</script>
</body>
</html>

演示: