<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery分页图片切换</title>
<style>
.slider-container {
width: 600px;
margin: 0 auto;
position: relative;
}
.slider {
width: 100%;
height: 400px;
overflow: hidden;
position: relative;
}
.slider-images {
display: flex;
transition: transform 0.5s ease;
}
.slider-images img {
width: 100%;
flex-shrink: 0;
}
.pagination {
display: flex;
justify-content: center;
margin-top: 15px;
}
.pagination-dot {
width: 12px;
height: 12px;
border-radius: 50%;
background: #ccc;
margin: 0 5px;
cursor: pointer;
}
.pagination-dot.active {
background: #333;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0,0,0,0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
z-index: 10;
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
.footer {
text-align: center;
margin-top: 30px;
color: #666;
}
</style>
</head>
<body>
<div class="slider-container">
<div class="slider">
<div class="slider-images">
<img src="https://picsum.photos/600/400?random=1" alt="图片1">
<img src="https://picsum.photos/600/400?random=2" alt="图片2">
<img src="https://picsum.photos/600/400?random=3" alt="图片3">
<img src="https://picsum.photos/600/400?random=4" alt="图片4">
<img src="https://picsum.photos/600/400?random=5" alt="图片5">
</div>
<button class="prev">❮</button>
<button class="next">❯</button>
</div>
<div class="pagination"></div>
</div>
<div class="footer">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
const $slider = $('.slider-images');
const $images = $('.slider-images img');
const $pagination = $('.pagination');
const imageCount = $images.length;
let currentIndex = 0;
const imageWidth = $('.slider').width();
// 初始化分页点
for (let i = 0; i < imageCount; i++) {
$pagination.append('<div class="pagination-dot" data-index="' + i + '"></div>');
}
// 设置第一个点为激活状态
$('.pagination-dot').first().addClass('active');
// 更新滑块位置
function updateSlider() {
$slider.css('transform', 'translateX(-' + (currentIndex * imageWidth) + 'px)');
$('.pagination-dot').removeClass('active');
$('.pagination-dot[data-index="' + currentIndex + '"]').addClass('active');
}
// 点击分页点切换图片
$('.pagination-dot').click(function() {
currentIndex = parseInt($(this).attr('data-index'));
updateSlider();
});
// 下一张按钮
$('.next').click(function() {
currentIndex = (currentIndex + 1) % imageCount;
updateSlider();
});
// 上一张按钮
$('.prev').click(function() {
currentIndex = (currentIndex - 1 + imageCount) % imageCount;
updateSlider();
});
// 自动轮播
let autoSlide = setInterval(function() {
$('.next').click();
}, 3000);
// 鼠标悬停时暂停轮播
$('.slider-container').hover(
function() {
clearInterval(autoSlide);
},
function() {
autoSlide = setInterval(function() {
$('.next').click();
}, 3000);
}
);
});
</script>
</body>
</html>
jQuery实现分页图片切换
1062

被折叠的 条评论
为什么被折叠?



