写一个html轮播图完整代码
时间: 2023-12-25 20:30:10 浏览: 84
以下是一个完整的HTML轮播图的代码示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<style>
.slideshow-container {
position: relative;
max-width: 100%;
margin: auto;
}
.slide {
display: none;
position: absolute;
width: 100%;
height: 100%;
}
.slide img {
width: 100%;
height: 100%;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
font-weight: bold;
padding: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
cursor: pointer;
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
.dots {
text-align: center;
margin-top: 20px;
}
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.5);
margin: 0 5px;
cursor: pointer;
}
.dot.active {
background-color: white;
}
</style>
</head>
<body>
<div class="slideshow-container">
<div class="slide">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="slide">
<img src="image2.jpg" alt="Image 2">
</div>
<div class="slide">
<img src="image3.jpg" alt="Image 3">
</div>
<a class="prev">❮</a>
<a class="next">❯</a>
<div class="dots">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
<script>
var slides = document.getElementsByClassName("slide");
var dots = document.getElementsByClassName("dot");
var currentSlide = 0;
function showSlide(n) {
if (n < 0) {
currentSlide = slides.length - 1;
} else if (n >= slides.length) {
currentSlide = 0;
} else {
currentSlide = n;
}
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (var i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[currentSlide].style.display = "block";
dots[currentSlide].className += " active";
}
function nextSlide() {
showSlide(currentSlide + 1);
}
function prevSlide() {
showSlide(currentSlide - 1);
}
function setSlide(n) {
showSlide(n);
}
var prevButton = document.querySelector(".prev");
var nextButton = document.querySelector(".next");
prevButton.addEventListener("click", prevSlide);
nextButton.addEventListener("click", nextSlide);
for (var i = 0; i < dots.length; i++) {
dots[i].addEventListener("click", function() {
var dotIndex = Array.prototype.indexOf.call(dots, this);
setSlide(dotIndex);
});
}
showSlide(currentSlide);
</script>
</body>
</html>
```
阅读全文