js实现li轮播
实现 li 轮播的 JavaScript 方法
HTML 结构
确保有一个包含 li 元素的容器,例如:

<ul id="slider">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button id="prev">Previous</button>
<button id="next">Next</button>
CSS 样式
为轮播添加基础样式,隐藏非活动项:

#slider {
list-style: none;
padding: 0;
position: relative;
height: 200px;
overflow: hidden;
}
#slider li {
position: absolute;
width: 100%;
opacity: 0;
transition: opacity 0.5s;
}
#slider li.active {
opacity: 1;
}
JavaScript 逻辑
通过切换 active 类控制显示项:
const slider = document.getElementById('slider');
const items = slider.querySelectorAll('li');
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
let currentIndex = 0;
// 初始化显示第一项
items[currentIndex].classList.add('active');
// 下一项函数
function showNext() {
items[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % items.length;
items[currentIndex].classList.add('active');
}
// 上一项函数
function showPrev() {
items[currentIndex].classList.remove('active');
currentIndex = (currentIndex - 1 + items.length) % items.length;
items[currentIndex].classList.add('active');
}
// 绑定按钮事件
nextBtn.addEventListener('click', showNext);
prevBtn.addEventListener('click', showPrev);
// 自动轮播(可选)
setInterval(showNext, 3000);
扩展功能:平滑滑动效果
若需水平滑动效果,修改 CSS 和 JavaScript:
#slider li {
position: absolute;
width: 100%;
left: 100%;
transition: left 0.5s;
}
#slider li.active {
left: 0;
}
#slider li.prev {
left: -100%;
}
function showNext() {
items[currentIndex].classList.remove('active');
items[currentIndex].classList.add('prev');
currentIndex = (currentIndex + 1) % items.length;
items[currentIndex].classList.add('active');
}
注意事项
- 确保
li的父容器有明确的宽度和overflow: hidden。 - 若需无限循环,使用取模运算(
%)处理索引越界。 - 自动轮播时,建议在用户交互时清除定时器以避免冲突。






