js实现轮播图完整代码
时间: 2023-12-06 12:03:28 浏览: 34
以下是一个简单的 JavaScript 实现轮播图的完整代码:
HTML 代码:
```html
<div class="slider">
<div class="slider-wrapper">
<img src="img1.jpg" alt="Image 1">
<img src="img2.jpg" alt="Image 2">
<img src="img3.jpg" alt="Image 3">
</div>
<div class="slider-nav">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slider-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
}
.slider-wrapper img {
width: 100%;
height: 100%;
object-fit: cover;
}
.slider-nav {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.slider-nav button {
padding: 10px 20px;
margin: 0 10px;
font-size: 16px;
color: #fff;
background-color: #333;
border: none;
border-radius: 5px;
cursor: pointer;
}
```
JavaScript 代码:
```javascript
const sliderWrapper = document.querySelector('.slider-wrapper');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
const images = document.querySelectorAll('.slider-wrapper img');
let currentIndex = 0;
const slideWidth = images[0].clientWidth;
function slideToIndex(index) {
sliderWrapper.style.transform = `translateX(-${index * slideWidth}px)`;
currentIndex = index;
}
function slidePrev() {
if (currentIndex === 0) {
slideToIndex(images.length - 1);
} else {
slideToIndex(currentIndex - 1);
}
}
function slideNext() {
if (currentIndex === images.length - 1) {
slideToIndex(0);
} else {
slideToIndex(currentIndex + 1);
}
}
prevBtn.addEventListener('click', slidePrev);
nextBtn.addEventListener('click', slideNext);
```
上述代码实现了一个简单的轮播图,包括:
- HTML 结构:包含轮播图容器、图片容器和导航按钮。
- CSS 样式:设置轮播图容器、图片容器和导航按钮的样式。
- JavaScript 逻辑:实现轮播图的核心逻辑,包括图片切换、导航按钮点击事件等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)