背景轮播
html部分
<div class="container"><div class="slide active" style="background-image: url(./static/20180529205331_yhGyf.jpeg);"></div><div class="slide " style="background-image: url(./static/20190214214253_hsjqw.webp);" ></div><div class="slide " style="background-image: url(./static/20190908084721_rjhtr.png);"></div><div class="slide " style="background-image: url(./static/20200205192210_tKHiT.jpeg);"></div><div class="slide " style="background-image: url(./static/20210210111704_cd68b.jpg);"></div><div class="left-btn"><i class="iconfont icon-up"></i></div><div class="right-btn"><i class="iconfont icon-arrdown"></i></div>
</div>
css部分
* {margin: 0;padding: 0;
}body {display: flex;flex-direction: column;align-items: center;justify-content: center;height: 100vh;overflow: hidden;position: relative;transition: all .4s;background-position: center;background-repeat: no-repeat;background-size: cover;
}body::after {content: "";position: absolute;inset: 0;background-color: rgba(0, 0, 0, 0.7);z-index: -1;
}.container {box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16),0 3px 6px rgba(0, 0, 0, 0.23);height: 70vh;width: 50vw;position: relative;overflow: hidden;z-index: 999;}.slide{position: absolute;opacity: 0;height: 70vh;width: 70vw;background-position: center;background-repeat: no-repeat;background-size: cover;transition: all .4s;
}
.slide.active{opacity: 1;z-index: 999;
}.left-btn{position: fixed;top: 50%;left: 21%;border: 2px solid white;padding: 10px;z-index: -1;cursor: pointer;
}
.right-btn{position: fixed;top: 50%;right: 21%;border: 2px solid white;padding: 10px;z-index: -1;cursor: pointer;
}.iconfont{color: white;font-size: 42px !important;
}
js部分
// 获取dom
const body=document.querySelector("body");
const slides=document.querySelectorAll(".slide");
const left_btn=document.querySelector(".left-btn");
const right_btn=document.querySelector(".right-btn");// 初始值背景
let activeSlide=0;
set_bg()// 右侧循环
right_btn.addEventListener("click",()=>{activeSlide++if(activeSlide>slides.length-1){activeSlide=0}set_bg()
})// 左侧循环
left_btn.addEventListener("click",()=>{activeSlide--if(activeSlide<0){activeSlide=slides.length-1}set_bg()
})// 设置内外背景
function set_bg(){body.style.backgroundImage=slides[activeSlide].style.backgroundImageslides.forEach((item)=>{item.classList.remove("active")})slides[activeSlide].classList.add("active")
}
效果