第228练最终效果如下:
HTML:
<!DOCTYPE html><html lang=”en”><head><meta charset=”UTF-8″ /><meta http-equiv=”X-UA-Compatible” content=”IE=edge” /><meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /><title>第228练</title><linkrel=”stylesheet”href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css”integrity=”sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==”crossorigin=”anonymous”referrerpolicy=”no-referrer”/><link rel=”stylesheet” href=”index.css” /></head><body><div class=”slider-container”><div class=”image-container”><img src=”https://picsum.photos/id/237/500/300″ alt=”image” /><img src=”https://picsum.photos/id/1/500/300″ alt=”image” /><img src=”https://picsum.photos/id/10/500/300″ alt=”image” /><img src=”https://picsum.photos/id/20/500/300″ alt=”image” /><img src=”https://picsum.photos/id/200/500/300″ alt=”image” /></div><i class=”fas fa-angle-double-left btn prev”></i><i class=”fas fa-angle-double-right btn next”></i></div><script src=”index.js”></script></body></html>
CSS:
body {margin: 0;display: flex;justify-content: center;height: 100vh;align-items: center;background-color: #fafafa;}.slider-container {position: relative;width: 500px;overflow: hidden;height: 300px;border-radius: 10px;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);}.image-container {display: flex;transition: transform 0.4s ease-in-out;}.btn {position: absolute;top: 50%;transform: translateY(-50%);color: white;font-size: 20px;opacity: 0.5;cursor: pointer;}.btn.prev {left: 10px;}.btn.next {right: 10px;}.btn:hover {opacity: 1;}
JS:
const nextEl = document.querySelector(“.next”);const prevEl = document.querySelector(“.prev”);const imgsEl = document.querySelectorAll(“img”);const imageContainerEl = document.querySelector(“.image-container”);let currentImg = 1;let timeout;nextEl.addEventListener(“click”, () => {currentImg++;clearTimeout(timeout);updateImg();});prevEl.addEventListener(“click”, () => {currentImg–;clearTimeout(timeout);updateImg();});updateImg();function updateImg() {if (currentImg > imgsEl.length) {currentImg = 1;} else if (currentImg < 1) {currentImg = imgsEl.length;}imageContainerEl.style.transform = `translateX(-${(currentImg – 1) * 500}px)`;timeout = setTimeout(() => {currentImg++;updateImg();}, 3000);}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...