本文概述
当你将鼠标指针漫游到所选元素上时, 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>
立即测试
评论前必须登录!
注册