轮播图html代码和js和css
时间: 2023-07-28 16:07:38 浏览: 89
轮播图css、html代码.rar
好的,以下是一个简单的轮播图的 HTML、CSS 和 JavaScript 代码示例:
HTML 代码:
```html
<div class="slider">
<div class="slide">
<img src="slide1.jpg" alt="Slide 1">
</div>
<div class="slide">
<img src="slide2.jpg" alt="Slide 2">
</div>
<div class="slide">
<img src="slide3.jpg" alt="Slide 3">
</div>
<div class="controls">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slide.active {
opacity: 1;
z-index: 1;
}
.controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
button {
padding: 10px 20px;
border: none;
background-color: #fff;
color: #333;
cursor: pointer;
}
button:focus {
outline: none;
}
button.next {
margin-left: 20px;
}
```
JavaScript 代码:
```js
const slides = document.querySelectorAll('.slide');
const nextBtn = document.querySelector('.next');
const prevBtn = document.querySelector('.prev');
let currentSlide = 0;
// show the first slide
slides[currentSlide].classList.add('active');
// next button click handler
nextBtn.addEventListener('click', () => {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add('active');
});
// previous button click handler
prevBtn.addEventListener('click', () => {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide - 1 + slides.length) % slides.length;
slides[currentSlide].classList.add('active');
});
// automatic slide show
setInterval(() => {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add('active');
}, 5000);
```
这段代码实现了一个基础的轮播图,包括自动播放和手动切换两种方式。你可以根据需要修改 CSS 样式和 JavaScript 代码以适应你的项目需求。
阅读全文