js实现简单轮播
实现简单轮播的 JavaScript 方法
HTML 结构
<div class="slider">
<div class="slides">
<img src="image1.jpg" class="slide active">
<img src="image2.jpg" class="slide">
<img src="image3.jpg" class="slide">
</div>
<button class="prev">←</button>
<button class="next">→</button>
</div>
CSS 样式
.slider {
position: relative;
width: 600px;
height: 400px;
margin: 0 auto;
overflow: hidden;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
height: 400px;
object-fit: cover;
}
.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; }
JavaScript 逻辑
const slides = document.querySelectorAll('.slide');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentIndex = 0;
function updateSlide() {
slides.forEach((slide, index) => {
slide.classList.toggle('active', index === currentIndex);
});
}
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + slides.length) % slides.length;
updateSlide();
});
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % slides.length;
updateSlide();
});
// 自动轮播
setInterval(() => {
currentIndex = (currentIndex + 1) % slides.length;
updateSlide();
}, 3000);
增强版轮播(带指示器)
HTML 添加指示器
<div class="indicators"></div>
CSS 添加样式
.indicators {
display: flex;
justify-content: center;
margin-top: 10px;
}
.indicator {
width: 12px;
height: 12px;
border-radius: 50%;
background: #ccc;
margin: 0 5px;
cursor: pointer;
}
.indicator.active {
background: #333;
}
JavaScript 更新
const indicatorsContainer = document.querySelector('.indicators');
// 创建指示器
slides.forEach((_, index) => {
const indicator = document.createElement('div');
indicator.classList.add('indicator');
if(index === 0) indicator.classList.add('active');
indicator.addEventListener('click', () => {
currentIndex = index;
updateSlide();
});
indicatorsContainer.appendChild(indicator);
});
function updateSlide() {
slides.forEach((slide, index) => {
slide.classList.toggle('active', index === currentIndex);
});
document.querySelectorAll('.indicator').forEach((indicator, index) => {
indicator.classList.toggle('active', index === currentIndex);
});
}
响应式轮播技巧
使用 CSS 媒体查询确保轮播适应不同屏幕尺寸:
@media (max-width: 768px) {
.slider {
width: 100%;
height: 300px;
}
.slide {
height: 300px;
}
}
性能优化建议
避免使用 setInterval 可能导致的问题,改用 requestAnimationFrame:
let lastTime = 0;
const delay = 3000;
function autoSlide(timestamp) {
if(timestamp - lastTime > delay) {
currentIndex = (currentIndex + 1) % slides.length;
updateSlide();
lastTime = timestamp;
}
requestAnimationFrame(autoSlide);
}
requestAnimationFrame(autoSlide);






