轮播图(Carousel)是一种常见的网页设计元素,用于展示一系列的图片或内容,并且可以自动或手动切换显示不同的项。下面是一个使用原生JavaScript实现简单轮播图的示例。
轮播图通常包含以下几个部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="carousel-item">
<img src="image2.jpg" alt="Image 2">
</div>
<div class="carousel-item">
<img src="image3.jpg" alt="Image 3">
</div>
</div>
<button class="carousel-control prev">❮</button>
<button class="carousel-control next">❯</button>
<div class="carousel-indicators">
<span class="indicator active"></span>
<span class="indicator"></span>
<span class="indicator"></span>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
.carousel {
position: relative;
width: 80%;
margin: 0 auto;
}
.carousel-inner {
position: relative;
overflow: hidden;
}
.carousel-item {
display: none;
width: 100%;
}
.carousel-item.active {
display: block;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0, 0, 0, 0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
.carousel-control.prev {
left: 0;
}
.carousel-control.next {
right: 0;
}
.carousel-indicators {
text-align: center;
margin-top: 10px;
}
.indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: gray;
margin: 0 5px;
cursor: pointer;
}
.indicator.active {
background: black;
}
// script.js
document.addEventListener('DOMContentLoaded', function() {
const items = document.querySelectorAll('.carousel-item');
const indicators = document.querySelectorAll('.indicator');
let currentIndex = 0;
function showItem(index) {
items.forEach((item, i) => {
item.classList.remove('active');
indicators[i].classList.remove('active');
});
items[index].classList.add('active');
indicators[index].classList.add('active');
}
function nextItem() {
currentIndex = (currentIndex + 1) % items.length;
showItem(currentIndex);
}
function prevItem() {
currentIndex = (currentIndex - 1 + items.length) % items.length;
showItem(currentIndex);
}
document.querySelector('.carousel-control.next').addEventListener('click', nextItem);
document.querySelector('.carousel-control.prev').addEventListener('click', prevItem);
indicators.forEach((indicator, index) => {
indicator.addEventListener('click', () => {
currentIndex = index;
showItem(currentIndex);
});
});
// 自动播放功能
setInterval(nextItem, 3000);
});
通过以上步骤和代码示例,你可以实现一个基本的轮播图功能,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云