前言
在上一篇文章JS特效篇:简单轮播图中,我们讲述了如何使用CSS+JS实现一个简单轮播图。本文将讲述如何通过CSS+JS,实现一个带指示器的轮播图,并详细讲解其中的原理和关键代码。
效果预览
在简单轮播图中,我们可以通过点击轮播区域,切换到下一张图片;但我们不能切换到上一张图,也不能随机切换图片。带指示器的轮播图就可以很好解决这一问题,通过指示器随意对轮播图片进行切换,其效果图如下所示:
代码实现
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>带指示器的轮播图</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.carousel-container {
width: 750px;
height: 400px;
position: relative;
overflow: hidden;
border-radius: 10px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
background-color: rgba(0, 0, 0, 0.1);
}
.carousel-slides {
display: flex;
height: 100%;
transition: transform 0.5s ease-in-out;
}
.carousel-slide {
min-width: 100%;
height: 100%;
position: relative;
}
.carousel-slide img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
.carousel-slide .caption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
padding: 20px;
color: white;
opacity: 1;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.carousel-slide .caption h3 {
font-size: 18px;
margin-bottom: 5px;
}
.carousel-slide .caption p {
font-size: 14px;
color: #f0f0f0;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
background-color: rgba(255, 255, 255, 0.2);
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
transition: background-color 0.3s;
z-index: 10;
backdrop-filter: blur(3px);
}
.prev-btn {
left: 15px;
}
.next-btn {
right: 15px;
}
.carousel-indicators {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 8px;
}
.carousel-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.5);
cursor: pointer;
transition: all 0.3s;
}
.carousel-indicator.active {
background-color: white;
transform: scale(1.2);
box-shadow: 0 0 5px rgba(255, 255, 255, 0.7);
}
</style>
</head>
<body>
<div class="carousel-container">
<div class="carousel-slides" id="carousel-slides">
<div class="carousel-slide">
<img src="https://picsum.photos/id/29/750/400" alt="雪山耸立">
<div class="caption">
<h3>雪山耸立</h3>
<p>宁静的雪山顶漂浮白云朵朵</p>
</div>
</div>
<div class="carousel-slide">
<img src="https://picsum.photos/id/10/750/400" alt="林中小湖">
<div class="caption">
<h3>林中小湖</h3>
<p>山林之间的平静小湖</p>
</div>
</div>
<div class="carousel-slide">
<img src="https://picsum.photos/id/28/750/400" alt="山中峡谷">
<div class="caption">
<h3>山中峡谷</h3>
<p>探索壮丽的自然奇观</p>
</div>
</div>
</div>
<div class="carousel-control prev-btn" id="prev-btn">
<span>❮</span>
</div>
<div class="carousel-control next-btn" id="next-btn">
<span>❯</span>
</div>
<div class="carousel-indicators" id="carousel-indicators">
<div class="carousel-indicator active" data-index="0"></div>
<div class="carousel-indicator" data-index="1"></div>
<div class="carousel-indicator" data-index="2"></div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const slidesContainer = document.getElementById('carousel-slides');
const slides = document.querySelectorAll('.carousel-slide');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const indicators = document.querySelectorAll('.carousel-indicator');
let currentIndex = 0; // 用于记录当前显示的图片索引
const slideCount = slides.length; // 获取图片总数
let autoplayInterval; // 存储自动播放的定时器 ID
let isPlaying = true; // 标记当前轮播图是否处于自动播放状态
const autoplayDuration = 3000; // 3秒切换一次
// 更新轮播位置和背景图片
function updateCarousel() {
slidesContainer.style.transform = `translateX(-${currentIndex * 100}%)`;
// 更新指示器状态
indicators.forEach((indicator, index) => {
if (index === currentIndex) {
indicator.classList.add('active');
} else {
indicator.classList.remove('active');
}
});
}
// 下一张
function nextSlide() {
currentIndex = (currentIndex + 1) % slideCount;
updateCarousel();
}
// 上一张
function prevSlide() {
currentIndex = (currentIndex - 1 + slideCount) % slideCount;
updateCarousel();
}
// 开始自动播放
function startAutoplay() {
autoplayInterval = setInterval(nextSlide, autoplayDuration);
isPlaying = true;
}
// 停止自动播放
function stopAutoplay() {
clearInterval(autoplayInterval);
isPlaying = false;
}
// 点击轮播图切换到下一张
slidesContainer.addEventListener('click', (e) => {
stopAutoplay();
nextSlide();
setTimeout(startAutoplay, autoplayDuration);
});
// 鼠标悬停暂停自动播放
const carouselContainer = document.querySelector('.carousel-container');
carouselContainer.addEventListener('mouseenter', stopAutoplay);
carouselContainer.addEventListener('mouseleave', startAutoplay);
// 点击事件绑定
nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
// 指示器点击事件
indicators.forEach(indicator => {
indicator.addEventListener('click', () => {
currentIndex = parseInt(indicator.dataset.index);
updateCarousel();
});
});
// 点击轮播图切换到下一张
slidesContainer.addEventListener('click', (e) => {
// 排除按钮点击
if (!e.target.closest('.carousel-control')) {
nextSlide();
}
});
// 初始化
updateCarousel();
startAutoplay();
});
</script>
</body>
</html>
代码说明
HTML结构
<div class="carousel-container">
<div class="carousel-slides" id="carousel-slides">
<div class="carousel-slide">
<img src="https://picsum.photos/id/29/750/400" alt="雪山耸立">
</div>
<div class="carousel-slide">
<img src="https://picsum.photos/id/10/750/400" alt="林中小湖">
</div>
<div class="carousel-slide">
<img src="https://picsum.photos/id/28/750/400" alt="山中峡谷">
</div>
</div>
</div>
<div class="carousel-container">
<div class="carousel-slides" id="carousel-slides">
<div class="carousel-slide">
<img src="https://picsum.photos/id/29/750/400" alt="雪山耸立">
<div class="caption">
<h3>雪山耸立</h3>
<p>宁静的雪山顶漂浮白云朵朵</p>
</div>
</div>
<div class="carousel-slide">
<img src="https://picsum.photos/id/10/750/400" alt="林中小湖">
<div class="caption">
<h3>林中小湖</h3>
<p>山林之间的平静小湖</p>
</div>
</div>
<div class="carousel-slide">
<img src="https://picsum.photos/id/28/750/400" alt="山中峡谷">
<div class="caption">
<h3>山中峡谷</h3>
<p>探索壮丽的自然奇观</p>
</div>
</div>
</div>
<div class="carousel-control prev-btn" id="prev-btn">
<span>❮</span>
</div>
<div class="carousel-control next-btn" id="next-btn">
<span>❯</span>
</div>
<div class="carousel-indicators" id="carousel-indicators">
<div class="carousel-indicator active" data-index="0"></div>
<div class="carousel-indicator" data-index="1"></div>
<div class="carousel-indicator" data-index="2"></div>
</div>
</div>
HTML结构说明
在上述代码中:
- 和简单轮播图相比,带指示器的轮播图HTML结构多了三个DIV样式:
prev-btn
、next-btn
和carousel-indicators
。 prev-btn
为向左箭头指示器,用于切换上一张图片。next-btn
为向右箭头指示器,用于切换下一张图片。carousel-indicators
为下方圆点指示器,用于随机切换图片。
CSS样式
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.carousel-container {
width: 750px;
height: 400px;
position: relative;
overflow: hidden;
border-radius: 10px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
background-color: rgba(0, 0, 0, 0.1);
}
.carousel-slides {
display: flex;
height: 100%;
transition: transform 0.5s ease-in-out;
}
.carousel-slide {
min-width: 100%;
height: 100%;
position: relative;
}
.carousel-slide img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
.carousel-slide .caption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
padding: 20px;
color: white;
opacity: 1;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.carousel-slide .caption h3 {
font-size: 18px;
margin-bottom: 5px;
}
.carousel-slide .caption p {
font-size: 14px;
color: #f0f0f0;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
background-color: rgba(255, 255, 255, 0.2);
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
transition: background-color 0.3s;
z-index: 10;
backdrop-filter: blur(3px);
}
.prev-btn {
left: 15px;
}
.next-btn {
right: 15px;
}
.carousel-indicators {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 8px;
}
.carousel-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.5);
cursor: pointer;
transition: all 0.3s;
}
.carousel-indicator.active {
background-color: white;
transform: scale(1.2);
box-shadow: 0 0 5px rgba(255, 255, 255, 0.7);
}
</style>
CSS样式说明
在上述代码中:
- 箭头指示器样式:
.carousel-control
通过绝对定位,让箭头指示器在图上垂直居中,.prev-btn
和.next-btn
分别在图片两边形成一个向左和向右的箭头。 - 圆点指示器:
.carousel-indicators
为原点指示器容器,内部通过.carousel-indicator
定义了多个圆点指示器,同时使用.carousel-indicator.active
标记当前被激活的圆点指示器。
JS逻辑
<script>
document.addEventListener('DOMContentLoaded', function() {
const slidesContainer = document.getElementById('carousel-slides');
const slides = document.querySelectorAll('.carousel-slide');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const indicators = document.querySelectorAll('.carousel-indicator');
let currentIndex = 0; // 用于记录当前显示的图片索引
const slideCount = slides.length; // 获取图片总数
let autoplayInterval; // 存储自动播放的定时器 ID
let isPlaying = true; // 标记当前轮播图是否处于自动播放状态
const autoplayDuration = 3000; // 3秒切换一次
// 更新轮播位置和背景图片
function updateCarousel() {
slidesContainer.style.transform = `translateX(-${currentIndex * 100}%)`;
// 更新指示器状态
indicators.forEach((indicator, index) => {
if (index === currentIndex) {
indicator.classList.add('active');
} else {
indicator.classList.remove('active');
}
});
}
// 下一张
function nextSlide() {
currentIndex = (currentIndex + 1) % slideCount;
updateCarousel();
}
// 上一张
function prevSlide() {
currentIndex = (currentIndex - 1 + slideCount) % slideCount;
updateCarousel();
}
// 开始自动播放
function startAutoplay() {
autoplayInterval = setInterval(nextSlide, autoplayDuration);
isPlaying = true;
}
// 停止自动播放
function stopAutoplay() {
clearInterval(autoplayInterval);
isPlaying = false;
}
// 点击轮播图切换到下一张
slidesContainer.addEventListener('click', (e) => {
stopAutoplay();
nextSlide();
setTimeout(startAutoplay, autoplayDuration);
});
// 鼠标悬停暂停自动播放
const carouselContainer = document.querySelector('.carousel-container');
carouselContainer.addEventListener('mouseenter', stopAutoplay);
carouselContainer.addEventListener('mouseleave', startAutoplay);
// 点击事件绑定
nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
// 指示器点击事件
indicators.forEach(indicator => {
indicator.addEventListener('click', () => {
currentIndex = parseInt(indicator.dataset.index);
updateCarousel();
});
});
// 点击轮播图切换到下一张
slidesContainer.addEventListener('click', (e) => {
// 排除按钮点击
if (!e.target.closest('.carousel-control')) {
nextSlide();
}
});
// 初始化
updateCarousel();
startAutoplay();
});
</script>
JS逻辑说明
相比简单轮播图,带指示器的轮播图增加了以下JS功能:
- updateCarousel:该方法除了实现图片切换外,还需要更新圆点指示器状态。
- prevSlide:新增了计算上一张图片的索引的方法,使用取余%运算确保有效索引,并调用
updateCarousel
更新轮播图。 - 箭头指示器事件监听:添加左右箭头监听器,实现点击不同箭头时,轮播图上一张/下一张图片切换。
- 圆点指示器事件监听:添加圆点指示器监听,实现轮播图随机切换。
结语
本文主要介绍了如何通过CSS+JS实现一个带指示器的轮播图,在后面的文章中,我会继续探讨其他类型的轮播图,你还知道哪些轮播图?欢迎在评论区留言分享!