jquery实现轮播图
实现基础轮播图结构
使用HTML创建轮播图的基本结构,包含图片容器和导航按钮。示例结构如下:
<div class="slider">
<div class="slides">
<img src="image1.jpg" class="active">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<button class="prev">←</button>
<button class="next">→</button>
</div>
添加CSS样式
为轮播图添加基础样式,确保图片水平排列且只显示当前活动图片:
.slider {
position: relative;
width: 800px;
height: 400px;
overflow: hidden;
}
.slides img {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease;
}
.slides img.active {
opacity: 1;
}
button {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 10;
}
.prev { left: 10px; }
.next { right: 10px; }
编写jQuery核心逻辑
通过jQuery实现图片切换功能,包含自动轮播和手动导航:

$(document).ready(function(){
let currentIndex = 0;
const slides = $('.slides img');
const totalSlides = slides.length;
// 手动切换函数
function showSlide(index) {
slides.removeClass('active').eq(index).addClass('active');
}
// 下一张按钮
$('.next').click(function(){
currentIndex = (currentIndex + 1) % totalSlides;
showSlide(currentIndex);
});
// 上一张按钮
$('.prev').click(function(){
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
showSlide(currentIndex);
});
// 自动轮播
let interval = setInterval(function(){
$('.next').click();
}, 3000);
// 鼠标悬停暂停
$('.slider').hover(
function() { clearInterval(interval); },
function() {
interval = setInterval(function(){ $('.next').click(); }, 3000);
}
);
});
添加指示器功能
扩展功能增加分页指示器,在HTML中添加:
<div class="dots-container"></div>
对应jQuery代码补充:

// 创建指示器
slides.each(function(index){
$('.dots-container').append(`<span class="dot" data-index="${index}"></span>`);
});
// 指示器点击事件
$('.dot').click(function(){
currentIndex = $(this).data('index');
showSlide(currentIndex);
});
// 更新当前指示器状态
function updateDots() {
$('.dot').removeClass('active').eq(currentIndex).addClass('active');
}
// 在showSlide函数内调用updateDots()
添加过渡动画效果
修改CSS实现更平滑的过渡效果,例如淡入淡出:
.slides img {
transition: opacity 0.5s ease, transform 0.5s ease;
transform: scale(1.05);
}
.slides img.active {
transform: scale(1);
}
响应式处理
添加窗口大小变化时的响应式调整:
$(window).resize(function(){
$('.slider').height($('.slider').width() * 0.5);
}).trigger('resize');






