小米商城轮播图代码
时间: 2023-07-09 08:12:19 浏览: 132
小米商城轮播图代码可以参考如下:
HTML部分:
```html
<div class="carousel">
<ul class="carousel-list">
<li class="carousel-item active">
<img src="image1.jpg" alt="图片1">
</li>
<li class="carousel-item">
<img src="image2.jpg" alt="图片2">
</li>
<li class="carousel-item">
<img src="image3.jpg" alt="图片3">
</li>
</ul>
<ul class="carousel-indicators">
<li class="active"></li>
<li></li>
<li></li>
</ul>
</div>
```
CSS部分:
```css
.carousel {
position: relative;
width: 100%;
height: 300px;
}
.carousel-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
list-style: none;
margin: 0;
padding: 0;
}
.carousel-item {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: all 0.5s ease-in-out;
}
.carousel-item.active {
opacity: 1;
}
.carousel-indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
list-style: none;
margin: 0;
padding: 0;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin-right: 10px;
cursor: pointer;
}
.carousel-indicators li.active {
background-color: #f40;
}
```
JavaScript部分:
```js
// 获取轮播元素
var carousel = document.querySelector('.carousel');
var carouselList = carousel.querySelector('.carousel-list');
var carouselItems = carouselList.querySelectorAll('.carousel-item');
var carouselIndicators = carousel.querySelector('.carousel-indicators').querySelectorAll('li');
var currentIndex = 0;
var timer;
// 显示指定的轮播项
function showCarouselItem(index) {
// 更新当前轮播项索引
currentIndex = index;
// 更新轮播项的显示状态
carouselItems.forEach(function(item, i) {
if (i === currentIndex) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
// 更新指示器的显示状态
carouselIndicators.forEach(function(indicator, i) {
if (i === currentIndex) {
indicator.classList.add('active');
} else {
indicator.classList.remove('active');
}
});
}
// 开始轮播
function startCarousel() {
timer = setInterval(function() {
var nextIndex = currentIndex + 1;
if (nextIndex >= carouselItems.length) {
nextIndex = 0;
}
showCarouselItem(nextIndex);
}, 3000);
}
// 停止轮播
function stopCarousel() {
clearInterval(timer);
}
// 绑定事件
carousel.addEventListener('mouseover', function() {
stopCarousel();
});
carousel.addEventListener('mouseout', function() {
startCarousel();
});
carouselIndicators.forEach(function(indicator, i) {
indicator.addEventListener('click', function() {
showCarouselItem(i);
});
});
// 显示第一项轮播项
showCarouselItem(0);
// 开始轮播
startCarousel();
```
阅读全文