前言
在上一篇文章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;
}
.out-carousel-container {
width: 750px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
background-size: cover;
background-position: center;
transition: background-image 0.5s ease-in-out;
}
.carousel-container {
width: 90%;
height: 90%;
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: none;
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;
transform: translateY(100%);
opacity: 0;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.carousel-slide:hover{
border: 2px solid white;
border-radius: 10px;
}
.carousel-slide:hover .caption {
transform: translateY(0);
opacity: 1;
}
.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);
}
.carousel-control:hover {
background-color: rgba(255, 255, 255, 0.4);
transform: translateY(-50%) scale(1.05);
}
.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="out-carousel-container" id="out-carousel-container">
<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>
</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');
const outContainer = document.getElementById('out-carousel-container');
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}%)`;
// 获取当前幻灯片的图片URL
const currentImage = slides[currentIndex].querySelector('img');
const imageUrl = currentImage.src;
// 更新外部容器的背景图片
outContainer.style.backgroundImage = `url(${imageUrl})`;
// 更新指示器状态
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;
}
// 点击事件绑定
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="out-carousel-container" id="out-carousel-container">
<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>
</div>
HTML结构说明
在上述代码中:
- 和普通带指示器的轮播图相比,背景同步轮播图HTML结构只是在最外层多了一个
out-carousel-container
DIV样式。
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;
}
.out-carousel-container {
width: 750px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
background-size: cover;
background-position: center;
transition: background-image 0.5s ease-in-out;
}
.carousel-container {
width: 90%;
height: 90%;
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: none;
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;
transform: translateY(100%);
opacity: 0;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.carousel-slide:hover{
border: 2px solid white;
border-radius: 10px;
}
.carousel-slide:hover .caption {
transform: translateY(0);
opacity: 1;
}
.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);
}
.carousel-control:hover {
background-color: rgba(255, 255, 255, 0.4);
transform: translateY(-50%) scale(1.05);
}
.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样式说明
在上述代码中:
- 外层背景容器:
.out-carousel-container
定义了一个外层背景容器,将轮播图容器.carousel-container
放在其内部。 - 轮播图容器:
.carousel-container
宽/高设置为.out-carousel-container
的90%(具体数值根据自己需要调整),同时定义图片object-fit: none;object-position: center;
的属性,保证图片不自动调整,且从图片中心往外自动裁剪。
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');
const outContainer = document.getElementById('out-carousel-container');
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}%)`;
// 获取当前幻灯片的图片URL
const currentImage = slides[currentIndex].querySelector('img');
const imageUrl = currentImage.src;
// 更新外部容器的背景图片
outContainer.style.backgroundImage = `url(${imageUrl})`;
// 更新指示器状态
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;
}
// 点击事件绑定
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:该方法新增了更新外部容器的背景图片的功能。
结语
本文主要介绍了如何通过CSS+JS实现一个背景同步轮播图,在后面的文章中,我会继续探讨其他类型的轮播图,你还知道哪些轮播图?欢迎在评论区留言分享!