帮我写一个轮播图
时间: 2023-07-04 14:10:32 浏览: 127
手写的轮播图
好的,以下是一个简单的轮播图的示例代码:
HTML:
```html
<div class="slider">
<div class="slider-wrapper">
<img src="img1.jpg">
<img src="img2.jpg">
<img src="img3.jpg">
</div>
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
```
CSS:
```css
.slider {
position: relative;
max-width: 600px;
margin: 0 auto;
}
.slider-wrapper {
display: flex;
transition: transform 0.5s ease;
}
.slider-wrapper img {
width: 100%;
height: auto;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 1.5rem;
padding: 10px;
background-color: #fff;
border: none;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
```
JavaScript:
```javascript
const sliderWrapper = document.querySelector('.slider-wrapper');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
const imgWidth = sliderWrapper.firstElementChild.clientWidth;
let currentPosition = 0;
nextBtn.addEventListener('click', () => {
if (currentPosition > -imgWidth * (sliderWrapper.children.length - 1)) {
currentPosition -= imgWidth;
sliderWrapper.style.transform = `translateX(${currentPosition}px)`;
}
});
prevBtn.addEventListener('click', () => {
if (currentPosition < 0) {
currentPosition += imgWidth;
sliderWrapper.style.transform = `translateX(${currentPosition}px)`;
}
});
```
这个轮播图的思路是将多张图片放在一个容器内,通过控制容器的 transform 属性来实现滑动。点击 Prev 和 Next 按钮时,改变 currentPosition 的值,再将其赋给容器的 transform 属性即可。
阅读全文