html+css+js轮播图
时间: 2023-12-18 22:29:09 浏览: 111
以下是一个简单的HTML、CSS和JS轮播图的示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>轮播图</title>
<style>
.container {
width: 600px;
height: 400px;
position: relative;
overflow: hidden;
}
.container img {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.container img.active {
opacity: 1;
}
.controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.controls button {
background-color: #fff;
border: none;
margin-right: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<img src="img1.jpg" class="active">
<img src="img2.jpg">
<img src="img3.jpg">
</div>
<div class="controls">
<button onclick="prevSlide()">上一张</button>
<button onclick="nextSlide()">下一张</button>
</div>
<script>
var slides = document.querySelectorAll('.container img');
var currentSlide = 0;
function nextSlide() {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add('active');
}
function prevSlide() {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide - 1 + slides.length) % slides.length;
slides[currentSlide].classList.add('active');
}
setInterval(nextSlide, 5000);
</script>
</body>
</html>
```
这个轮播图使用了一个包含三张图片的容器,每张图片都是绝对定位的,并且默认情况下不可见。通过添加和删除“active”类来控制哪张图片可见。轮播图还包括两个按钮,用于手动切换图片。最后,使用JavaScript设置了一个定时器,每隔5秒钟自动切换到下一张图片。
阅读全文