js实现li轮播
实现 LI 轮播的 JavaScript 方法
HTML 结构
确保轮播内容包裹在 ul 或 ol 列表结构中,并为容器添加类名以便选择:
<div class="carousel-container">
<ul class="carousel-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button class="prev-btn">Previous</button>
<button class="next-btn">Next</button>
</div>
CSS 样式 为轮播容器和列表项添加基础样式,确保隐藏非活动项:
.carousel-container {
position: relative;
overflow: hidden;
width: 300px;
}
.carousel-list {
display: flex;
list-style: none;
padding: 0;
margin: 0;
transition: transform 0.5s ease;
}
.carousel-list li {
min-width: 100%;
padding: 20px;
box-sizing: border-box;
}
JavaScript 逻辑
通过修改 transform 属性实现平滑滑动效果:
document.addEventListener('DOMContentLoaded', () => {
const list = document.querySelector('.carousel-list');
const items = document.querySelectorAll('.carousel-list li');
const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
let currentIndex = 0;
function updateCarousel() {
list.style.transform = `translateX(-${currentIndex * 100}%)`;
}
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % items.length;
updateCarousel();
});
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + items.length) % items.length;
updateCarousel();
});
});
自动轮播功能扩展
添加定时器实现自动播放,并优化鼠标交互时的暂停:
let autoPlayInterval = setInterval(() => {
currentIndex = (currentIndex + 1) % items.length;
updateCarousel();
}, 3000);
// 鼠标悬停时暂停轮播
document.querySelector('.carousel-container').addEventListener('mouseenter', () => {
clearInterval(autoPlayInterval);
});
// 鼠标离开时恢复轮播
document.querySelector('.carousel-container').addEventListener('mouseleave', () => {
autoPlayInterval = setInterval(() => {
currentIndex = (currentIndex + 1) % items.length;
updateCarousel();
}, 3000);
});
响应式处理
通过监听窗口大小变化调整轮播布局:
function handleResize() {
const containerWidth = document.querySelector('.carousel-container').offsetWidth;
document.querySelectorAll('.carousel-list li').forEach(item => {
item.style.minWidth = `${containerWidth}px`;
});
updateCarousel();
}
window.addEventListener('resize', handleResize);
handleResize(); // 初始化执行
指示器添加
创建动态指示点以增强用户体验:
const indicators = document.createElement('div');
indicators.className = 'carousel-indicators';
document.querySelector('.carousel-container').appendChild(indicators);
items.forEach((_, index) => {
const dot = document.createElement('span');
dot.addEventListener('click', () => {
currentIndex = index;
updateCarousel();
updateIndicators();
});
indicators.appendChild(dot);
});
function updateIndicators() {
const dots = document.querySelectorAll('.carousel-indicators span');
dots.forEach((dot, index) => {
dot.classList.toggle('active', index === currentIndex);
});
}






