帮我用原生javascript写一个轮播图代码
时间: 2024-05-05 09:16:33 浏览: 124
下面是一个简单的原生 JavaScript 轮播图代码:
HTML:
```
<div class="slider">
<div class="slider-images">
<img src="image1.jpg" alt="">
<img src="image2.jpg" alt="">
<img src="image3.jpg" alt="">
<img src="image4.jpg" alt="">
</div>
<div class="slider-prev"></div>
<div class="slider-next"></div>
</div>
```
CSS:
```
.slider {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
}
.slider-images {
position: absolute;
top: 0;
left: 0;
width: 2400px;
height: 400px;
}
.slider-images img {
float: left;
width: 600px;
height: 400px;
}
.slider-prev,
.slider-next {
position: absolute;
top: 50%;
margin-top: -15px;
width: 30px;
height: 30px;
background-color: #333;
opacity: 0.5;
cursor: pointer;
}
.slider-prev {
left: 20px;
}
.slider-next {
right: 20px;
}
```
JavaScript:
```
var sliderImages = document.querySelector('.slider-images');
var sliderPrev = document.querySelector('.slider-prev');
var sliderNext = document.querySelector('.slider-next');
var imageWidth = document.querySelector('.slider-images img').clientWidth;
var imageCount = sliderImages.children.length;
var currentPosition = 0;
sliderPrev.addEventListener('click', function() {
if (currentPosition > 0) {
currentPosition--;
sliderImages.style.transform = 'translateX(' + (-imageWidth * currentPosition) + 'px)';
}
});
sliderNext.addEventListener('click', function() {
if (currentPosition < imageCount - 1) {
currentPosition++;
sliderImages.style.transform = 'translateX(' + (-imageWidth * currentPosition) + 'px)';
}
});
```
运行代码后,点击左右箭头可以实现轮播图的切换。您可以根据需要进行更改和优化。
阅读全文