写一个图片轮播html
时间: 2023-07-20 12:27:51 浏览: 111
好的,以下是一个简单的图片轮播的HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>图片轮播</title>
<style>
.container {
position: relative;
width: 100%;
height: 400px;
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 {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
.control {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background-color: #fff;
cursor: pointer;
}
.control.active {
background-color: #333;
}
</style>
</head>
<body>
<div class="container">
<div class="slide active">
<img src="https://dummyimage.com/600x400/000/fff" alt="Slide 1">
</div>
<div class="slide">
<img src="https://dummyimage.com/600x400/ccc/000" alt="Slide 2">
</div>
<div class="slide">
<img src="https://dummyimage.com/600x400/fff/333" alt="Slide 3">
</div>
<div class="controls">
<div class="control active"></div>
<div class="control"></div>
<div class="control"></div>
</div>
</div>
<script>
let slides = document.querySelectorAll('.slide');
let controls = document.querySelectorAll('.control');
let currentSlide = 0;
function resetSlides() {
for (let i = 0; i < slides.length; i++) {
slides[i].classList.remove('active');
controls[i].classList.remove('active');
}
}
function startSlide() {
resetSlides();
slides[0].classList.add('active');
controls[0].classList.add('active');
}
function slideLeft() {
resetSlides();
slides[currentSlide - 1].classList.add('active');
controls[currentSlide - 1].classList.add('active');
currentSlide--;
}
function slideRight() {
resetSlides();
slides[currentSlide + 1].classList.add('active');
controls[currentSlide + 1].classList.add('active');
currentSlide++;
}
controls.forEach(function(control, index) {
control.addEventListener('click', function() {
resetSlides();
control.classList.add('active');
slides[index].classList.add('active');
currentSlide = index;
});
});
startSlide();
setInterval(function() {
if (currentSlide === slides.length - 1) {
currentSlide = -1;
}
slideRight();
}, 5000);
</script>
</body>
</html>
```
这段代码使用了 CSS 的 `position` 属性和 JavaScript 的 `setInterval` 方法来实现图片轮播。在 HTML 中,我们创建了一个 `div` 元素作为容器,其中包含了若干个 `div` 元素作为轮播的每个图片,每个图片都使用了 `img` 元素来显示图片。同时,我们还创建了控制轮播的小圆点,使用了 JavaScript 来控制图片的切换和小圆点的状态。
阅读全文