jquery 走马灯
jQuery 走马灯实现方法
走马灯(轮播图)是网页常见的交互组件,以下是几种实现方式:
使用原生 jQuery 实现
基础结构需要HTML、CSS和jQuery代码配合:
<div class="carousel">
<div class="carousel-inner">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<button class="prev">←</button>
<button class="next">→</button>
</div>
.carousel {
position: relative;
width: 600px;
overflow: hidden;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease;
}
.carousel-inner img {
width: 100%;
flex-shrink: 0;
}
$(function(){
let currentIndex = 0;
const $inner = $('.carousel-inner');
const itemWidth = $inner.width();
$('.next').click(function(){
currentIndex++;
$inner.css('transform', `translateX(-${currentIndex * itemWidth}px)`);
});
$('.prev').click(function(){
currentIndex--;
$inner.css('transform', `translateX(-${currentIndex * itemWidth}px)`);
});
});
使用 jQuery 插件
Slick 是流行的 jQuery 轮播插件:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<div class="your-class">
<div><img src="image1.jpg"></div>
<div><img src="image2.jpg"></div>
<div><img src="image3.jpg"></div>
</div>
$('.your-class').slick({
dots: true,
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear'
});
自动轮播实现
在原生实现基础上添加定时器:
function autoPlay() {
setInterval(() => {
currentIndex = (currentIndex + 1) % $('.carousel-inner img').length;
$inner.css('transform', `translateX(-${currentIndex * itemWidth}px)`);
}, 3000);
}
autoPlay();
响应式处理
添加窗口大小变化时的适配:
$(window).resize(function() {
itemWidth = $inner.width();
$inner.css('transform', `translateX(-${currentIndex * itemWidth}px)`);
});
注意事项:

- 图片需要统一尺寸
- 移动端需添加触摸事件支持
- 无限循环需克隆首尾元素
- 插件方式更简单但会增加页面体积






