轮播图jquery
使用 jQuery 实现轮播图
基础 HTML 结构
创建一个包含轮播图项的容器,并添加导航按钮(如左右箭头和指示点)。
<div class="slider">
<div class="slides">
<div class="slide active">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<button class="prev">←</button>
<button class="next">→</button>
<div class="dots">
<span class="dot active"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
CSS 样式
为轮播图添加基本样式,确保轮播项水平排列并隐藏非活动项。
.slider {
position: relative;
width: 100%;
overflow: hidden;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
display: none;
}
.slide.active {
display: block;
}
.dots {
text-align: center;
margin-top: 10px;
}
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: #ccc;
margin: 0 5px;
cursor: pointer;
}
.dot.active {
background: #333;
}
jQuery 实现逻辑
通过 jQuery 控制轮播图的切换、自动播放及导航功能。

$(document).ready(function() {
const $slides = $('.slides');
const $slide = $('.slide');
const $nextBtn = $('.next');
const $prevBtn = $('.prev');
const $dots = $('.dot');
let currentIndex = 0;
const totalSlides = $slide.length;
// 切换到指定索引的幻灯片
function goToSlide(index) {
if (index >= totalSlides) index = 0;
if (index < 0) index = totalSlides - 1;
currentIndex = index;
$slides.css('transform', `translateX(-${currentIndex * 100}%)`);
$slide.removeClass('active').eq(index).addClass('active');
$dots.removeClass('active').eq(index).addClass('active');
}
// 下一张幻灯片
$nextBtn.click(function() {
goToSlide(currentIndex + 1);
});
// 上一张幻灯片
$prevBtn.click(function() {
goToSlide(currentIndex - 1);
});
// 点击指示点跳转
$dots.click(function() {
const dotIndex = $(this).index();
goToSlide(dotIndex);
});
// 自动轮播(可选)
let autoPlay = setInterval(() => {
goToSlide(currentIndex + 1);
}, 3000);
// 鼠标悬停时暂停轮播
$slides.hover(
() => clearInterval(autoPlay),
() => autoPlay = setInterval(() => goToSlide(currentIndex + 1), 3000)
);
});
功能扩展
- 无限循环:通过检查边界条件(如
index >= totalSlides时重置为 0)实现无缝轮播。 - 动画效果:使用 CSS
transition或 jQueryanimate()实现平滑切换。 - 响应式适配:通过监听窗口大小变化调整轮播图尺寸。
注意事项
- 确保 jQuery 库已引入,例如:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> - 若需兼容旧版浏览器,可添加 CSS 前缀或降级方案。






