18.背景轮播

背景轮播

html部分

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.backgroundImage

    slides.forEach((item)=>{
        item.classList.remove("active")
    })
    slides[activeSlide].classList.add("active")
}

效果

你可能感兴趣的:(前端开发50个案例,前端,javascript)