原生JavaScript实现轮播图
时间: 2023-05-23 17:01:13 浏览: 226
非常好的问题!以下是一个基本的原生 JavaScript 轮播图实现:
HTML
```html
<div class="slider">
<div class="slider-wrapper">
<div class="slider-item"></div>
<div class="slider-item"></div>
<div class="slider-item"></div>
</div>
<div class="slider-nav">
<a class="slider-prev" href="#">Prev</a>
<a class="slider-next" href="#">Next</a>
</div>
</div>
```
CSS
```css
.slider {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.slider-wrapper {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 300%;
display: flex;
transition: transform 0.3s ease-in-out;
}
.slider-item {
height: 100%;
width: 33.333%;
}
.slider-nav {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
z-index: 10;
display: flex;
}
.slider-prev,
.slider-next {
margin: 0 10px;
padding: 5px 10px;
background-color: #ddd;
border-radius: 3px;
}
.slider-prev:hover,
.slider-next:hover {
background-color: #bbb;
}
```
JavaScript
```js
const sliderWrapper = document.querySelector('.slider-wrapper');
const prevBtn = document.querySelector('.slider-prev');
const nextBtn = document.querySelector('.slider-next');
const sliderItems = document.querySelectorAll('.slider-item');
const itemWidth = sliderItems[0].offsetWidth;
let position = 0;
nextBtn.addEventListener('click', () => {
position -= itemWidth;
if (position < -itemWidth * (sliderItems.length - 1)) {
position = 0;
}
moveToPosition();
});
prevBtn.addEventListener('click', () => {
position += itemWidth;
if (position > 0) {
position = -itemWidth * (sliderItems.length - 1);
}
moveToPosition();
});
function moveToPosition() {
sliderWrapper.style.transform = `translateX(${position}px)`;
}
```
这个例子通过改变 sliderWrapper 的 transform 属性来移动轮播图的位置。prevBtn 和 nextBtn 的点击事件分别减小或增加 position 值,而 moveToPosition 函数将新的 position 值应用到 sliderWrapper 上,实现轮播图的效果。
阅读全文