本篇实现的是轮播图淡入淡出的效果,思路是利用图片的层级替换实现的,运用了屏幕的自适应属性。
1.HTML代码
代码语言:javascript复制 <div class="swiper-container">
<div class="swiper-wrapper">
<img src="../image/1.jpg" alt="">
<img src="../image/2.jpg" alt="">
<img src="../image/3.jpg" alt="">
<img src="../image/4.jpg" alt="">
<img src="../image/5.jpg" alt="">
</div>
</div>
2.css代码
代码语言:javascript复制.swiper-container{
position: relative;
}
.swiper-wrapper{
position: absolute;
}
.swiper-wrapper img{
display:block;
position: absolute;
}
3.js代码
代码语言:javascript复制window.onload=function(){
let swiperContainer = document.getElementsByClassName('swiper-container')[0];
let wrap=document.getElementsByClassName("swiper-wrapper")[0];
let wrapImg = document.getElementsByClassName("swiper-wrapper")[0].getElementsByTagName('img')
//获取屏幕的宽度
let windowWidth = window.screen.width;
let wrapImgLeng = wrapImg.length;
let timer=null;
let index = -1;
//屏幕宽度
for(let i = 0 ;i < wrapImgLeng;i ){
wrapImg[i].style.width = windowWidth 'px'
}
//淡入淡出效果,用的是层级的一个循环
function swiper(){
clearInterval(timer);
opacity=1;
if( index == wrapImgLeng){
index=0;
}
for(let i=0;i<wrapImgLeng;i ){
wrapImg[i].style.opacity=1;
if(index!=i){
wrapImg[i].style.zIndex=1;
}
}
timer=setInterval(function(){
if(opacity<=0){
clearInterval(timer);
setTimeout(function(){
swiper();
},3000);
}
opacity -=0.01;
console.log(index)
wrapImg[index].style.zIndex=3;
wrapImg[index].style.opacity=opacity;
if(index == wrapImgLeng -1){
wrapImg[0].style.zIndex=2;
}else{
wrapImg[index 1].style.zIndex=2;
}
},30);
}
swiper();
}