一、准备工作
在开始之前,请确保你的网页中已经引入了jQuery库。以下是引入jQuery的常用方法:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
二、HTML结构
<div id="image-slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2" style="display: none;">
<img src="image3.jpg" alt="Image 3" style="display: none;">
<button id="next">Next</button>
</div>
三、CSS样式
#image-slider img {
width: 100%;
height: auto;
display: none;
}
#image-slider img.active {
display: block;
}
四、jQuery脚本
$(document).ready(function() {
var currentImage = 0;
var images = $('#image-slider img');
function showImage(index) {
images.removeClass('active').eq(index).addClass('active');
}
$('#next').click(function() {
currentImage = (currentImage + 1) % images.length;
showImage(currentImage);
});
});
五、完整示例
以下是整合了HTML、CSS和jQuery的完整示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Slider</title>
<style>
#image-slider img {
width: 100%;
height: auto;
display: none;
}
#image-slider img.active {
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var currentImage = 0;
var images = $('#image-slider img');
function showImage(index) {
images.removeClass('active').eq(index).addClass('active');
}
$('#next').click(function() {
currentImage = (currentImage + 1) % images.length;
showImage(currentImage);
});
});
</script>
</head>
<body>
<div id="image-slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2" style="display: none;">
<img src="image3.jpg" alt="Image 3" style="display: none;">
<button id="next">Next</button>
</div>
</body>
</html>