Jquery hover()
当您将鼠标指针漫游到所选元素上时,jQuery hover()方法将执行两个功能。 hover()方法同时触发mouseenter和mouseleave事件。
语法:
$(selector).hover(inFunction,outFunction)
注意: 如果仅指定一个函数,则将同时为mouseenter和mouseleave事件运行该函数。
jQuery hover()事件的参数
参数 |
说明 |
InFunction |
这是必填参数。当发生mouseenter事件时,将执行该功能。 |
OutFunction |
这是一个可选参数。当发生mouseleave事件时,将执行该功能。 |
jQuery hover()示例
让我们举个例子来看看hover()效果。在此示例中,将鼠标指针悬停在所选元素上时,该所选元素的背景颜色将更改。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("p").hover(function(){
$(this).css("background-color", "violet");
}, function(){
$(this).css("background-color", "green");
});
});
</script>
</head>
<body>
<p>Hover your mouse pointer on me!</p>
</body>
</html>
输出:
注意: 在上面的示例中,所选元素的背景色对于mouseenter事件是紫色,对于mouseleave事件是绿色。
jQuery hover()示例2
让我们看看结合了fadeIn和fadeOut效果的hover()事件的另一个示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover demo</title>
<style>
ul {
margin-left: 20px;
color: black;
}
li {
cursor: default;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<ul>
<li>Java</li>
<li>SQL</li>
<li class="fade">Android</li>
<li class="fade">php</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>
输出: