轮播图是网页中高频出现的交互组件,原生js实现轮播图不需要依赖第三方库,核心是通过dom操作、定时器控制和事件监听配合完成。下面先介绍基础的页面结构,再逐步拆解实现步骤。

一、基础页面结构搭建
首先需要准备轮播图的容器、图片列表、指示点和切换按钮,结构如下:
<div class="carousel">
<ul class="carousel-list">
<li><img src="https://ipipp.com/img1.jpg" alt="轮播图1"></li>
<li><img src="https://ipipp.com/img2.jpg" alt="轮播图2"></li>
<li><img src="https://ipipp.com/img3.jpg" alt="轮播图3"></li>
</ul>
<div class="indicators">
<span class="active"></span>
<span></span>
<span></span>
</div>
<button class="prev-btn">上一张</button>
<button class="next-btn">下一张</button>
</div>
对应的基础样式需要让图片横向排列,容器溢出隐藏,这里给出核心样式:
.carousel {
width: 800px;
height: 400px;
position: relative;
overflow: hidden;
margin: 0 auto;
}
.carousel-list {
width: 300%;
height: 100%;
padding: 0;
margin: 0;
list-style: none;
display: flex;
transition: transform 0.3s ease;
}
.carousel-list li {
width: 33.333%;
height: 100%;
}
.carousel-list img {
width: 100%;
height: 100%;
object-fit: cover;
}
.indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 10px;
}
.indicators span {
width: 10px;
height: 10px;
border-radius: 50%;
background: #ccc;
cursor: pointer;
}
.indicators .active {
background: #fff;
}
.prev-btn, .next-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px 15px;
cursor: pointer;
}
.prev-btn { left: 10px; }
.next-btn { right: 10px; }
二、js实现轮播图的5个关键步骤
步骤1:获取dom元素并定义初始状态
首先需要拿到轮播图相关的所有dom节点,同时定义当前展示的图片索引、图片总数等初始变量,为后续操作做铺垫。
// 获取dom元素
const carouselList = document.querySelector('.carousel-list');
const indicators = document.querySelectorAll('.indicators span');
const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
const carousel = document.querySelector('.carousel');
// 初始状态定义
let currentIndex = 0; // 当前图片索引
const imgCount = indicators.length; // 图片总数
let timer = null; // 定时器变量
步骤2:实现图片切换核心函数
切换图片的核心逻辑是修改轮播列表的transform属性,同时更新指示点的激活状态,这一步是后续所有切换操作的基础。
// 切换图片的核心函数
function switchImg(index) {
// 边界处理,索引超出范围时循环
if (index >= imgCount) {
index = 0;
} else if (index < 0) {
index = imgCount - 1;
}
currentIndex = index;
// 计算偏移量,每张图片宽度是容器宽度
const offset = -currentIndex * 800;
carouselList.style.transform = `translateX(${offset}px)`;
// 更新指示点状态
indicators.forEach((item, i) => {
if (i === currentIndex) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
步骤3:绑定手动切换事件
给上一张、下一张按钮绑定点击事件,点击时调用切换函数修改索引即可,同时给指示点绑定点击切换事件。
// 下一张按钮事件
nextBtn.addEventListener('click', () => {
switchImg(currentIndex + 1);
resetTimer(); // 手动切换后重置定时器
});
// 上一张按钮事件
prevBtn.addEventListener('click', () => {
switchImg(currentIndex - 1);
resetTimer(); // 手动切换后重置定时器
});
// 指示点点击事件
indicators.forEach((item, index) => {
item.addEventListener('click', () => {
switchImg(index);
resetTimer(); // 手动切换后重置定时器
});
});
步骤4:实现自动轮播功能
使用setInterval创建定时器,每隔固定时间自动切换到下一张图片,实现自动轮播效果。
// 启动自动轮播
function startTimer() {
timer = setInterval(() => {
switchImg(currentIndex + 1);
}, 3000); // 每3秒切换一次
}
// 重置定时器,避免手动切换后定时器叠加
function resetTimer() {
clearInterval(timer);
startTimer();
}
// 初始化时启动定时器
startTimer();
步骤5:添加鼠标悬停暂停功能
为了提升用户体验,当鼠标悬停在轮播图上时暂停自动轮播,移出时恢复自动轮播。
// 鼠标悬停暂停轮播
carousel.addEventListener('mouseenter', () => {
clearInterval(timer);
});
// 鼠标移出恢复轮播
carousel.addEventListener('mouseleave', () => {
startTimer();
});
三、完整代码整合
将所有逻辑整合后,就可以得到一个完整的原生js轮播图,完整js代码如下:
// 获取dom元素
const carouselList = document.querySelector('.carousel-list');
const indicators = document.querySelectorAll('.indicators span');
const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
const carousel = document.querySelector('.carousel');
// 初始状态定义
let currentIndex = 0;
const imgCount = indicators.length;
let timer = null;
// 切换图片的核心函数
function switchImg(index) {
if (index >= imgCount) {
index = 0;
} else if (index < 0) {
index = imgCount - 1;
}
currentIndex = index;
const offset = -currentIndex * 800;
carouselList.style.transform = `translateX(${offset}px)`;
indicators.forEach((item, i) => {
if (i === currentIndex) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
// 下一张按钮事件
nextBtn.addEventListener('click', () => {
switchImg(currentIndex + 1);
resetTimer();
});
// 上一张按钮事件
prevBtn.addEventListener('click', () => {
switchImg(currentIndex - 1);
resetTimer();
});
// 指示点点击事件
indicators.forEach((item, index) => {
item.addEventListener('click', () => {
switchImg(index);
resetTimer();
});
});
// 启动自动轮播
function startTimer() {
timer = setInterval(() => {
switchImg(currentIndex + 1);
}, 3000);
}
// 重置定时器
function resetTimer() {
clearInterval(timer);
startTimer();
}
// 鼠标悬停暂停轮播
carousel.addEventListener('mouseenter', () => {
clearInterval(timer);
});
// 鼠标移出恢复轮播
carousel.addEventListener('mouseleave', () => {
startTimer();
});
// 初始化启动轮播
startTimer();
按照以上5个步骤就可以完成一个功能完整的原生js轮播图,核心逻辑可以复用在各种类似的交互组件中,理解这些步骤也能帮助掌握原生js操作dom和事件处理的基础能力。