返回
0. 一个轻量的轮播图
前端
2023-12-12 05:37:43
在构建前端项目时,轮播图组件通常是不可或缺的。但很多时候,我们并不需要复杂的动画和样式,仅仅需要一个轻量且实用的轮播图效果。依赖第三方库当然是一种简单便捷的方式,但这些库往往体积庞大,对项目性能带来不必要的负担。
因此,我们可以考虑自己动手编写一个最轻量的轮播图。这里,我们将从以下几个关键点出发,一步步构建我们的轮播图组件:
- 翻页按钮 :在轮播图的左右两侧放置翻页按钮,用于手动切换图片。
- 分页器 :在轮播图的下方添加分页器,用于指示当前显示的图片序号和总图片数。
- 悬停静止 :当鼠标悬停在轮播图上时,暂停自动轮播。
- 无限轮播 :当轮播图到达最后一张图片时,自动跳转到第一张图片,实现无限轮播效果。
- 清理动画叠加 :当用户快速点击翻页按钮时,可能导致动画叠加,因此需要在动画结束后清理动画队列。
首先,在HTML中定义轮播图容器,并为其添加一个类名,如carousel-container
。在容器内,放置轮播图图片,并为每张图片添加一个类名,如carousel-image
。
<div class="carousel-container">
<img class="carousel-image" src="image1.jpg" alt="Image 1">
<img class="carousel-image" src="image2.jpg" alt="Image 2">
<img class="carousel-image" src="image3.jpg" alt="Image 3">
</div>
接下来,在CSS中为轮播图容器和图片设置样式,并为翻页按钮和分页器添加样式。
.carousel-container {
width: 100%;
height: 300px;
overflow: hidden;
}
.carousel-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.carousel-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
.carousel-button.left {
left: 0;
}
.carousel-button.right {
right: 0;
}
.carousel-pager {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
display: flex;
justify-content: center;
}
.carousel-pager-item {
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background-color: #ffffff;
}
.carousel-pager-item.active {
background-color: #000000;
}
最后,在JavaScript中编写轮播图的逻辑代码,包括翻页按钮的点击事件、自动轮播和悬停静止等功能。
const carouselContainer = document.querySelector('.carousel-container');
const carouselImages = document.querySelectorAll('.carousel-image');
const carouselButtons = document.querySelectorAll('.carousel-button');
const carouselPager = document.querySelector('.carousel-pager');
const carouselPagerItems = document.querySelectorAll('.carousel-pager-item');
let currentImageIndex = 0;
let autoPlayInterval;
// 翻页按钮点击事件
carouselButtons.forEach((button, index) => {
button.addEventListener('click', () => {
currentImageIndex = index === 0 ? currentImageIndex - 1 : currentImageIndex + 1;
showImage(currentImageIndex);
});
});
// 自动轮播
function startAutoPlay() {
autoPlayInterval = setInterval(() => {
currentImageIndex++;
showImage(currentImageIndex);
}, 3000);
}
// 悬停静止
carouselContainer.addEventListener('mouseenter', () => {
clearInterval(autoPlayInterval);
});
carouselContainer.addEventListener('mouseleave', () => {
startAutoPlay();
});
// 显示图片
function showImage(index) {
if (index < 0) {
currentImageIndex = carouselImages.length - 1;
} else if (index >= carouselImages.length) {
currentImageIndex = 0;
}
carouselImages.forEach((image, imageIndex) => {
image.style.display = imageIndex === currentImageIndex ? 'block' : 'none';
});
carouselPagerItems.forEach((item, itemIndex) => {
item.classList.remove('active');
});
carouselPagerItems[currentImageIndex].classList.add('active');
}
// 初始化
showImage(currentImageIndex);
startAutoPlay();
至此,我们就完成了一个轻量且实用的轮播图组件。它包含了翻页按钮、分页器、悬停静止、无限轮播和清理动画叠加等功能,完全可以满足一般项目的轮播需求。