jquery图片切换
jQuery 图片切换实现方法
基础图片轮播
通过简单的 fadeIn() 和 fadeOut() 方法实现淡入淡出效果:
let currentIndex = 0;
const images = $('.slider img');
const totalImages = images.length;
function changeImage() {
images.eq(currentIndex).fadeOut(500);
currentIndex = (currentIndex + 1) % totalImages;
images.eq(currentIndex).fadeIn(500);
}
setInterval(changeImage, 3000);
带控制按钮的切换
添加前进/后退按钮控制:
$('#next').click(function() {
$('.active').removeClass('active').next().addClass('active');
if (!$('.active').length) {
$('.slider img').first().addClass('active');
}
});
$('#prev').click(function() {
$('.active').removeClass('active').prev().addClass('active');
if (!$('.active').length) {
$('.slider img').last().addClass('active');
}
});
缩略图导航
点击缩略图切换主图:
$('.thumbnail').click(function() {
const newSrc = $(this).attr('src');
$('#main-image').attr('src', newSrc);
});
滑动切换效果
使用 animate() 实现水平滑动:
$('#slider-container').animate(
{left: '-=200px'},
600,
function() {
$(this).css('left', '0').append($('img:first'));
}
);
自动/手动切换模式
添加暂停/播放控制:

let autoPlay = setInterval(changeSlide, 3000);
$('#pause').click(function() {
clearInterval(autoPlay);
});
$('#play').click(function() {
autoPlay = setInterval(changeSlide, 3000);
});
注意事项
- 确保在文档加载完成后执行脚本:
$(document).ready(function() {...}); - 为图片容器设置固定尺寸避免布局抖动
- 考虑添加预加载机制提升用户体验
- 移动端需添加触摸事件支持
完整示例结构
<div class="slider">
<img src="1.jpg" class="active">
<img src="2.jpg">
<img src="3.jpg">
</div>
<button id="prev">Previous</button>
<button id="next">Next</button>






