html轮播图主要代码
时间: 2024-10-31 10:06:39 浏览: 6
html实现图片轮播(含代码和注释)
HTML轮播图通常是通过CSS和JavaScript配合来实现的,常见的库有swiper、owl-carousel等。这里简单介绍一个基础的HTML+CSS+JavaScript轮播图实现:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.carousel {
width: 600px;
overflow: hidden;
}
.carousel-item {
display: none; /* 隐藏初始图片 */
position: absolute; /* 使用绝对定位 */
}
.carousel-item.active {
display: block; /* 当前图片显示 */
}
.carousel-dot {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}
.carousel-dot li {
display: inline-block;
cursor: pointer;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin-right: 5px;
}
.carousel-dot li.active {
background-color: black;
}
</style>
</head>
<body>
<div class="carousel">
<img src="image1.jpg" alt="Slide 1" class="carousel-item active">
<img src="image2.jpg" alt="Slide 2" class="carousel-item">
<img src="image3.jpg" alt="Slide 3" class="carousel-item">
</div>
<ul class="carousel-dot">
<li class="active"></li>
<li></li>
<li></li>
</ul>
<script>
let slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
// 获取元素
var i;
var slides = document.getElementsByClassName("carousel-item");
var dots = document.getElementsByClassName("carousel-dot")[0].getElementsByTagName("li");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
// 隐藏所有图片
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
// 显示指定索引的图片
slides[slideIndex - 1].style.display = "block";
// 更新指示器
for (i = 0; i < dots.length; i++) {
dots[i].classList.remove('active');
}
dots[n - 1].classList.add('active');
}
</script>
</body>
</html>
```
阅读全文