9.1小T学前端
轮播图–渐隐显示
用透明度的方式来进行播放下一个,主要思路为:先清除所有的,再留自己。active为opacity: 1 。
1.HTML
<div class="swiper">
<div class="imgList">
<div class="imgItem active" style="background-image: url(3.img/img1.webp);"></div>
<div class="imgItem" style="background-image: url(3.img/img2.jpg);"></div>
<div class="imgItem" style="background-image: url(3.img/img3.webp);"></div>
<div class="imgItem" style="background-image: url(3.img/img4.webp);"></div>
<div class="imgItem" style="background-image: url(3.img/img5.webp);"></div>
</div>
<div class="btnList">
<div class="btn pre">
<</div>
<div class="btn next">></div>
</div>
</div>
</div>
2.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.swiper {
margin: 100px auto;
}
.swiper,
.imgList {
width: 613px;
height: 230px;
position: relative;
}
.imgItem {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-size: 100% 100%;
opacity: 0;
transition: all 0.3s;
}
.active {
opacity: 1;
}
.btn {
width: 50px;
height: 60px;
font-size: 20px;
opacity: 0.3;
line-height: 50px;
background-color: #eee;
}
.pre {
position: absolute;
top: calc(50% - 25px);
cursor: pointer;
text-align: center;
}
.next {
position: absolute;
top: calc(50% - 25px);
right: 0;
cursor: pointer;
text-align: center;
}
.pre:hover,
.next:hover {
opacity: 0.5;
}
3.js
var prebtn = document.querySelector('.pre');
var nextbtn = document.querySelector('.next')
var imgItems = document.querySelectorAll('.imgItem')
console.log(imgItems);
n = 0;
prebtn.onclick = function() {
n--;
if (n < 0) {
n = imgItems.length - 1
}
imgItems.forEach(function(item, e) {
item.classList.remove('active')
})
imgItems[n].classList.add('active');
}
nextbtn.onclick = function() {
n++;
if (n > imgItems.length - 1) {
n = 0
}
imgItems.forEach(function(item, e) {
item.classList.remove('active')
})
imgItems[n].classList.add('active');
}