35.图片幻灯片

图片幻灯片

html部分


css部分

* {
    margin: 0;
    padding: 0;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    height: 100vh;
}

img {
    flex-shrink: 0;
    width: 100% !important;
    height: 100% !important; 
    object-fit: cover;
    transition: all .7s;
}

.carousel {
    box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.4);
    height: 530px;
    width: 500px;
    overflow: hidden;
}

.image-container {
    width: 500px;
    height: 500px;
    display: flex;
}   
.button-container{
    display: flex;
    height: 30px;
    color: #fff;
    line-height: 1.8;
    cursor: pointer;
}
.button-container div:first-child:active{
    transform: scaleY(0.98) ;
}
.button-container div:last-child:active{
    transform: scaleY(0.98);
}
.button-container div:first-child{
    flex: 1;
    text-align: center;
    margin-right: 5px;
    background: rebeccapurple;
}
.button-container div:last-child{
    flex: 1;
    text-align: center;
    background: rebeccapurple;
}

js部分

// 获取dom
const pre = document.querySelector(".pre");
const next = document.querySelector(".next");
const img_box = document.querySelector(".image-container")
const imgs = document.querySelectorAll("img")

// 初始活动元素
let active_index = 0

// 下移
next.addEventListener("click", function (e) {
    active_index++
    if (active_index > imgs.length - 1) {
        active_index = 0;
    }

    change_img()
})
// 上移
pre.addEventListener("click", function (e) {
    active_index--
    if (active_index < 0) {
        active_index = imgs.length - 1;
    }

    change_img()
})

// 所以元素前进或者后退
function change_img() {
    imgs.forEach((item) => {
        item.style.transform = `translate(${-active_index * 500}px)`
    })
}

效果

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