jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。轮播(Carousel)是一种网页设计元素,用于展示一系列图片或内容,通常具有自动播放和手动切换功能。
以下是一个简单的 jQuery 轮播图示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Carousel</title>
<style>
.carousel {
width: 600px;
overflow: hidden;
position: relative;
}
.carousel img {
width: 100%;
display: none;
}
.carousel img:first-child {
display: block;
}
.carousel .nav {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.carousel .nav button {
margin: 0 5px;
}
</style>
</head>
<body>
<div class="carousel">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<div class="nav">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
let currentIndex = 0;
const images = $('.carousel img');
const totalImages = images.length;
function showImage(index) {
images.hide();
images.eq(index).show();
}
$('.next').click(function() {
currentIndex = (currentIndex + 1) % totalImages;
showImage(currentIndex);
});
$('.prev').click(function() {
currentIndex = (currentIndex - 1 + totalImages) % totalImages;
showImage(currentIndex);
});
// 自动播放
setInterval(function() {
$('.next').click();
}, 3000);
});
</script>
</body>
</html>
setInterval
的时间间隔设置正确,并且没有被其他 JavaScript 代码中断。通过以上示例和解释,你应该能够理解并实现一个简单的 jQuery 轮播图。如果有更多具体问题,可以进一步提问。
领取专属 10元无门槛券
手把手带您无忧上云