图片幻灯片
html部分
<div class="carousel"><div class="image-container"><img src="./static/20180529205331_yhGyf.jpeg" alt="" srcset=""><img src="./static/20190214214253_hsjqw.webp" alt="" srcset=""><img src="./static/20190908084721_rjhtr.png" alt="" srcset=""><img src="./static/20200205192210_tKHiT.jpeg" alt="" srcset=""></div><div class="button-container"><div class="pre">pre</div><div class="next">next</div></div>
</div>
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)`})
}
效果