jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。通过 jQuery,你可以轻松地实现网页上的各种动态效果,包括图片切换。
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 图片切换</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.image-container {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.image-container img {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s 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">
<img src="image3.jpg" alt="Image 3">
</div>
<script>
$(document).ready(function() {
var images = $('.image-container img');
var currentIndex = 0;
function showImage(index) {
images.removeClass('active').css('opacity', 0);
images.eq(index).addClass('active').css('opacity', 1);
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
setInterval(nextImage, 3000); // 每 3 秒切换一次图片
});
</script>
</body>
</html>
function preloadImages(images) {
images.each(function() {
$('<img>').attr('src', $(this).attr('src'));
});
}
preloadImages($('.image-container img'));
.image-container img {
transition: opacity 0.5s ease-in-out;
}
currentIndex
的计算逻辑,确保每次切换到正确的图片。function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
通过以上方法,你可以实现一个简单且流畅的 jQuery 图片切换效果。
没有搜到相关的文章