CSS代码:
.image-slider {
position: relative;
max-width: 100%;
overflow: hidden;
padding: 20px; /* 添加外部空白 */
box-sizing: border-box; /* 确保padding不影响总宽度 */
background-color: #f9f9f9; /* 可选:设置背景颜色 */
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 250px; /* 图片最小宽度 */
max-width: 250px; /* 图片最大宽度 */
margin: 0 10px; /* 在左右增加间隔 */
}
.slide img {
width: 100%;
height: auto;
border-radius: 8px; /* 可选:设置圆角 */
}
button {
position: absolute;
top: 50%;
background-color: rgba(255, 255, 255, 0.7);
border: none;
cursor: pointer;
padding: 10px;
transform: translateY(-50%);
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
button {
position: absolute;
top: 50%;
background-color: rgba(255, 255, 255, 0.8);
border: none;
cursor: pointer;
padding: 10px 15px;
border-radius: 50%; /* 圆形按钮 */
font-size: 24px; /* 增大字体大小 */
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5); /* 添加阴影效果 */
transition: background-color 0.3s; /* 添加过渡效果 */
}
button:hover {
background-color: rgba(255, 255, 255, 1); /* 悬停时增加透明度 */
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
javascript代码:
<script>
let currentIndex = 0;
const totalSlides = document.querySelectorAll('.slide').length;
const slides = document.querySelector('.slides');
// 自动循环滑动
const autoSlide = setInterval(() => {
moveSlide(1);
}, 3000); // 每3秒自动滑动一次
function moveSlide(direction) {
currentIndex += direction;
if (currentIndex < 0) {
currentIndex = totalSlides - 1; // 循环到最后一张
}
if (currentIndex >= totalSlides) {
currentIndex = 0; // 循环到第一张
}
const offset = -currentIndex * (250 + 20); // 250是每张照片的宽度,加上左右间隔
slides.style.transform = `translateX(${offset}px)`;
}
</script>
区块
<div class="image-slider">
<div class="slides">
<div class="slide"><img src="图片地址" alt="Image 1"></div>
<div class="slide"><img src="图片地址" alt="Image 2"></div>
<div class="slide"><img src="图片地址" alt="Image 3"></div>
<div class="slide"><img src="图片地址" alt="Image 4"></div>
<div class="slide"><img src="图片地址" alt="Image 5"></div>
<div class="slide"><img src="图片地址" alt="Image 6"></div>
</div>
<button class="prev" onclick="moveSlide(-1)">◀</button> <!-- 左箭头 -->
<button class="next" onclick="moveSlide(1)">▶</button> <!-- 右箭头 -->
</div>
豪堪