写一个JS原生卡片式轮播图
时间: 2023-12-11 13:54:37 浏览: 174
原生js轮播图
好的,我可以帮助你解决这个问题。以下是一个基本的JS原生卡片式轮播图的实现:
HTML:
```
<div class="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="img1.jpg" alt="Slide 1">
</div>
<div class="carousel-item">
<img src="img2.jpg" alt="Slide 2">
</div>
<div class="carousel-item">
<img src="img3.jpg" alt="Slide 3">
</div>
</div>
<a class="carousel-control-prev" href="#" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
```
CSS:
```
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-item {
position: relative;
display: none;
height: 100%;
width: 100%;
}
.carousel-item.active {
display: block;
}
.carousel-item img {
height: 100%;
width: 100%;
object-fit: cover;
}
.carousel-control-prev,
.carousel-control-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 1;
display: block;
width: 30px;
height: 30px;
}
.carousel-control-prev-icon,
.carousel-control-next-icon {
display: inline-block;
width: 100%;
height: 100%;
background-repeat: no-repeat;
background-position: center;
background-size: 100% 100%;
}
.carousel-control-prev-icon {
background-image: url('previous.png');
}
.carousel-control-next-icon {
background-image: url('next.png');
}
```
JS:
```
var carousel = document.querySelector('.carousel');
var carouselInner = document.querySelector('.carousel-inner');
var carouselItems = document.querySelectorAll('.carousel-item');
var carouselControlPrev = document.querySelector('.carousel-control-prev');
var carouselControlNext = document.querySelector('.carousel-control-next');
var activeIndex = 0;
function setActive(index) {
carouselItems[activeIndex].classList.remove('active');
carouselItems[index].classList.add('active');
activeIndex = index;
}
carouselControlPrev.addEventListener('click', function() {
var prevIndex = activeIndex === 0 ? carouselItems.length - 1 : activeIndex - 1;
setActive(prevIndex);
});
carouselControlNext.addEventListener('click', function() {
var nextIndex = activeIndex === carouselItems.length - 1 ? 0 : activeIndex + 1;
setActive(nextIndex);
});
```
这段代码实现了一个具有左右控制按钮和卡片式效果的轮播图。你可以根据自己的需求修改其中的HTML和CSS内容,以实现更加复杂和自定义的效果。
阅读全文