Jquery版轮播图超详细
以下是一个使用jQuery实现的轮播图的示例代码,包含了基本的功能和样式:
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 轮播图</title>
<style>
.carousel {
position: relative;
width: 300px;
height: 200px;
margin: auto;
}
.carousel-inner {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
.carousel-inner img {
width: 100%;
height: 100%;
}
.carousel-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.carousel-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin: 0 5px;
cursor: pointer;
}
.carousel-dot.active {
background-color: #333;
}
</style>
</head>
<body>
<div class="carousel">
<div class="carousel-inner">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<div class="carousel-dots">
<span class="carousel-dot active"></span>
<span class="carousel-dot"></span>
<span class="carousel-dot"></span>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
let $carousel = $('.carousel');
let $carouselInner = $carousel.find('.carousel-inner');
let $carouselDots = $carousel.find('.carousel-dots');
let $carouselDot = $carouselDots.find('.carousel-dot');
let currentIndex = 0;
function goToSlide(index) {
currentIndex = index;
$carouselInner.animate({ left: `-${100 * index}%` }, 500);
$carouselDot.eq(index).addClass('active').siblings().removeClass('active');
}
$carouselDot.on('click', function() {
let dotIndex = $(this).index();
goToSlide(dotIndex);
});
setInterval(function() {
let nextIndex = (currentIndex + 1) % $carouselDot.length;
goToSlide(nextIndex);
}, 3000);
});
</script>
</body>
</html>
这段代码实现了一个简单的自动轮播图,包括图片切换和点点导航。轮播图可以自动播放,并且可以通过点击对应的点点来手动切换图片。这个例子提供了一个基本的轮播图实现参考,可以根据实际需求进行功能扩展和样式调整。
评论已关闭