前端编写一段代码实现轮播图
时间: 2023-08-11 17:34:59 浏览: 72
前端JavaScript实现轮播图效果
好的,以下是一个简单的前端轮播图的代码示例:
HTML:
```html
<div class="slider-container">
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button class="prev-button">Prev</button>
<button class="next-button">Next</button>
</div>
```
CSS:
```css
.slider-container {
position: relative;
}
.slider {
display: flex;
overflow: hidden;
}
.slider img {
width: 100%;
height: auto;
}
.prev-button, .next-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 1;
background: transparent;
border: none;
cursor: pointer;
}
.prev-button {
left: 0;
}
.next-button {
right: 0;
}
```
JavaScript:
```js
const slider = document.querySelector('.slider');
const prevButton = document.querySelector('.prev-button');
const nextButton = document.querySelector('.next-button');
const imageWidth = slider.querySelector('img').clientWidth;
let currentPosition = 0;
prevButton.addEventListener('click', () => {
currentPosition = currentPosition + imageWidth;
if (currentPosition > 0) {
currentPosition = -(imageWidth * (slider.children.length - 1));
}
slider.style.transform = `translateX(${currentPosition}px)`;
});
nextButton.addEventListener('click', () => {
currentPosition = currentPosition - imageWidth;
if (currentPosition < -(imageWidth * (slider.children.length - 1))) {
currentPosition = 0;
}
slider.style.transform = `translateX(${currentPosition}px)`;
});
```
这段代码使用了 CSS 的 flexbox 布局实现水平排列图片,并使用 JavaScript 实现了点击按钮进行轮播的功能。
阅读全文