Wab前端开发轮播图
时间: 2023-09-22 21:07:31 浏览: 90
实现轮播图可以使用第三方库,比如Swiper、Slick等,也可以自己手动编写实现。以下是一份简单的自己手写轮播图的代码:
HTML部分:
```html
<div class="slider">
<ul class="slider-container">
<li class="slider-item"><img src="image1.jpg"></li>
<li class="slider-item"><img src="image2.jpg"></li>
<li class="slider-item"><img src="image3.jpg"></li>
</ul>
<ul class="slider-nav">
<li class="slider-nav-item active"></li>
<li class="slider-nav-item"></li>
<li class="slider-nav-item"></li>
</ul>
</div>
```
CSS部分:
```css
.slider {
position: relative;
width: 600px;
height: 300px;
overflow: hidden;
}
.slider-container {
position: relative;
width: 1800px;
height: 300px;
margin: 0;
padding: 0;
list-style: none;
}
.slider-item {
float: left;
width: 600px;
height: 300px;
}
.slider-nav {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
margin: 0;
padding: 0;
list-style: none;
z-index: 10;
}
.slider-nav-item {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 10px;
border-radius: 50%;
background-color: #ccc;
}
.slider-nav-item.active {
background-color: #333;
}
```
JavaScript部分:
```javascript
var slider = document.querySelector('.slider');
var sliderContainer = slider.querySelector('.slider-container');
var sliderItems = slider.querySelectorAll('.slider-item');
var sliderNav = slider.querySelector('.slider-nav');
var sliderNavItems = sliderNav.querySelectorAll('.slider-nav-item');
var currentIndex = 0;
var intervalId;
function initSlider() {
// 设置轮播图容器的宽度
sliderContainer.style.width = sliderItems.length * 100 + '%';
// 设置轮播图每一个item的宽度
for (var i = 0; i < sliderItems.length; i++) {
sliderItems[i].style.width = 100 / sliderItems.length + '%';
}
// 绑定导航点的click事件
for (var i = 0; i < sliderNavItems.length; i++) {
sliderNavItems[i].addEventListener('click', onNavItemClick);
}
// 开始自动轮播
startAutoPlay();
}
function onNavItemClick(event) {
var navItem = event.currentTarget;
var index = Array.prototype.indexOf.call(sliderNavItems, navItem);
currentIndex = index;
updateSlider();
}
function startAutoPlay() {
intervalId = setInterval(function() {
currentIndex = (currentIndex + 1) % sliderItems.length;
updateSlider();
}, 3000);
}
function stopAutoPlay() {
clearInterval(intervalId);
}
function updateSlider() {
sliderContainer.style.transform = 'translateX(-' + currentIndex * 100 / sliderItems.length + '%)';
for (var i = 0; i < sliderNavItems.length; i++) {
var navItem = sliderNavItems[i];
if (i === currentIndex) {
navItem.classList.add('active');
} else {
navItem.classList.remove('active');
}
}
}
initSlider();
```
这份代码实现了基本的轮播功能,并且提供了导航点(小圆点)供用户手动切换图片。你可以根据自己的需要进行修改和优化。
阅读全文