html+javascript实现轮播图效果
时间: 2023-09-23 11:04:09 浏览: 110
好的,以下是一个简单的HTML+JavaScript轮播图效果的实现:
HTML代码:
```html
<div class="slider">
<img class="slide" src="image1.jpg" alt="Image 1">
<img class="slide" src="image2.jpg" alt="Image 2">
<img class="slide" src="image3.jpg" alt="Image 3">
</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>
```
CSS代码:
```css
.slider {
position: relative;
width: 100%;
height: 500px;
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;
}
```
JavaScript代码:
```javascript
const slides = document.querySelectorAll(".slide");
const prevBtn = document.querySelector("#prevBtn");
const nextBtn = document.querySelector("#nextBtn");
let currentSlide = 0;
// 初始化轮播图
slides[currentSlide].classList.add("active");
// 上一张图片按钮点击事件
prevBtn.addEventListener("click", () => {
slides[currentSlide].classList.remove("active");
currentSlide = (currentSlide - 1 + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
});
// 下一张图片按钮点击事件
nextBtn.addEventListener("click", () => {
slides[currentSlide].classList.remove("active");
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add("active");
});
```
通过以上代码实现了一个简单的轮播图效果,点击“Prev”按钮可以切换到上一张图片,“Next”按钮可以切换到下一张图片。
阅读全文