jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。鼠标悬停(hover)事件是 jQuery 中的一个常用事件,用于检测鼠标指针是否悬停在某个元素上。
鼠标悬停切换图片是一种常见的交互效果,常用于导航菜单、图片展示等场景。
以下是一个使用 jQuery 实现鼠标悬停切换图片的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Hover Switch Images</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.image-container {
position: relative;
width: 300px;
height: 200px;
}
.image-container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.image-container img.active {
opacity: 1;
}
</style>
</head>
<body>
<div class="image-container">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
</div>
<script>
$(document).ready(function() {
$('.image-container').hover(
function() {
// 鼠标进入时切换到第二张图片
$(this).find('img').removeClass('active');
$(this).find('img:last-child').addClass('active');
},
function() {
// 鼠标离开时切换回第一张图片
$(this).find('img').removeClass('active');
$(this).find('img:first-child').addClass('active');
}
);
});
</script>
</body>
</html>
opacity
和 transition
属性来平滑过渡。通过以上示例代码和解决方法,你可以实现一个简单的鼠标悬停切换图片的效果。
领取专属 10元无门槛券
手把手带您无忧上云