jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。鼠标经过切换图片是一种常见的网页交互效果,通常用于导航菜单、产品展示等场景。
鼠标经过切换图片可以通过多种方式实现,常见的有以下几种:
:hover
伪类实现简单的图片切换。fadeIn
、fadeOut
)实现平滑的图片切换效果。以下是一个使用 jQuery 实现鼠标经过切换图片的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 鼠标经过切换图片</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.image-container {
position: relative;
width: 300px;
height: 200px;
overflow: hidden;
}
.image-container img {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.image-container img:first-child {
opacity: 1;
}
</style>
</head>
<body>
<div class="image-container">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<script>
$(document).ready(function() {
$('.image-container').hover(
function() {
$(this).find('img').each(function(index) {
if (index !== 0) {
$(this).stop().fadeIn(500);
}
});
},
function() {
$(this).find('img').each(function(index) {
if (index !== 0) {
$(this).stop().fadeOut(500);
}
});
}
);
});
</script>
</body>
</html>
通过以上方法,可以实现一个简单且流畅的鼠标经过切换图片效果。
领取专属 10元无门槛券
手把手带您无忧上云