用原生js实现左右翻页
时间: 2024-05-16 09:11:50 浏览: 13
可以使用以下代码实现左右翻页:
```javascript
// 获取需要翻页的元素
const slider = document.querySelector('.slider');
const sliderItems = document.querySelectorAll('.slider-item');
const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
// 初始化当前的活动索引
let activeIndex = 0;
// 左翻页
function prevPage() {
if (activeIndex === 0) {
activeIndex = sliderItems.length - 1;
} else {
activeIndex--;
}
displayPage();
}
// 右翻页
function nextPage() {
if (activeIndex === sliderItems.length - 1) {
activeIndex = 0;
} else {
activeIndex++;
}
displayPage();
}
// 显示当前页
function displayPage() {
sliderItems.forEach((item, index) => {
if (index === activeIndex) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
// 控制按钮点击事件
prevBtn.addEventListener('click', prevPage);
nextBtn.addEventListener('click', nextPage);
// 初始化显示第一页
displayPage();
```
注意:以上代码只是实现左右翻页的核心代码,需要结合 HTML 和 CSS 代码才能实现完整的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)