用js写一个轮播图
时间: 2023-09-02 08:09:39 浏览: 28
好的,以下是一个简单的基于 JavaScript 的轮播图实现:
HTML:
```html
<div class="slider">
<div class="slides">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<div class="controls">
<span class="prev">◀</span>
<span class="next">▶</span>
</div>
</div>
```
CSS:
```css
.slider {
position: relative;
width: 100%;
height: 400px;
}
.slides {
position: absolute;
width: 100%;
height: 100%;
display: flex;
transition: transform 0.5s ease-in-out;
}
.slides img {
width: 100%;
height: 100%;
object-fit: cover;
}
.controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.controls span {
display: inline-block;
width: 40px;
height: 40px;
font-size: 30px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 50%;
cursor: pointer;
text-align: center;
line-height: 40px;
margin-right: 10px;
transition: background-color 0.2s ease-in-out;
}
.controls span:hover {
background-color: rgba(0, 0, 0, 0.8);
}
```
JavaScript:
```javascript
const slider = document.querySelector('.slider');
const slides = slider.querySelector('.slides');
const prevBtn = slider.querySelector('.prev');
const nextBtn = slider.querySelector('.next');
const slideWidth = slides.getBoundingClientRect().width;
let currentIndex = 0;
function goToSlide(index) {
slides.style.transform = `translateX(-${index * slideWidth}px)`;
currentIndex = index;
}
function goToPrevSlide() {
if (currentIndex === 0) {
goToSlide(slides.children.length - 1);
} else {
goToSlide(currentIndex - 1);
}
}
function goToNextSlide() {
if (currentIndex === slides.children.length - 1) {
goToSlide(0);
} else {
goToSlide(currentIndex + 1);
}
}
prevBtn.addEventListener('click', goToPrevSlide);
nextBtn.addEventListener('click', goToNextSlide);
goToSlide(currentIndex);
setInterval(goToNextSlide, 3000);
```
这个轮播图采用了 flexbox 布局,通过设置 `transform` 属性来定位每一张图片。同时,通过监听左右箭头的点击事件以及使用 `setInterval` 定时器实现了自动轮播。
阅读全文