写一个轮播图的html文件
时间: 2024-05-07 07:07:52 浏览: 70
<!DOCTYPE html>
<html>
<head>
<title>轮播图</title>
<style>
body {
margin: 0;
padding: 0;
}
.slider {
width: 100%;
height: 500px;
position: relative;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slide.active {
opacity: 1;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
.arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 2rem;
color: white;
cursor: pointer;
}
.arrow.left {
left: 20px;
}
.arrow.right {
right: 20px;
}
.dots {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: white;
margin-right: 10px;
cursor: pointer;
}
.dot.active {
background-color: red;
}
</style>
</head>
<body>
<div class="slider">
<div class="slide active">
<img src="https://picsum.photos/1200/500?random=1" alt="Slide 1">
</div>
<div class="slide">
<img src="https://picsum.photos/1200/500?random=2" alt="Slide 2">
</div>
<div class="slide">
<img src="https://picsum.photos/1200/500?random=3" alt="Slide 3">
</div>
<div class="arrow left">❮</div>
<div class="arrow right">❯</div>
<div class="dots">
<div class="dot active"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
<script>
const slides = document.querySelectorAll('.slide');
const dots = document.querySelectorAll('.dot');
const prev = document.querySelector('.left');
const next = document.querySelector('.right');
let currentIndex = 0;
function reset() {
slides.forEach(slide => slide.classList.remove('active'));
dots.forEach(dot => dot.classList.remove('active'));
}
function showSlide(index) {
reset();
slides[index].classList.add('active');
dots[index].classList.add('active');
}
function goToPrev() {
if (currentIndex === 0) {
currentIndex = slides.length - 1;
} else {
currentIndex--;
}
showSlide(currentIndex);
}
function goToNext() {
if (currentIndex === slides.length - 1) {
currentIndex = 0;
} else {
currentIndex++;
}
showSlide(currentIndex);
}
prev.addEventListener('click', goToPrev);
next.addEventListener('click', goToNext);
dots.forEach((dot, index) => {
dot.addEventListener('click', () => {
currentIndex = index;
showSlide(currentIndex);
});
});
setInterval(goToNext, 5000);
</script>
</body>
</html>
阅读全文