我正在尝试创建一个滑块,但其中的卡片根本没有空格。我尝试在它们之间添加边距,但这不起作用。
你能帮我找出我哪里搞砸了吗?提前致谢。
const cards = document.querySelectorAll(".card"); const btnLeft = document.querySelector(".slider__btn--left"); const btnRight = document.querySelector(".slider__btn--right"); let currentCard = 0; const lastCard = cards.length; const goToCard = function(currCard) { cards.forEach( (card, index) => (card.style.transform = `translateX(${100 * (index - currCard)}%)`) ); }; goToCard(0); const nextCard = function() { if (currentCard === lastCard - 1) currentCard = 0; else currentCard++; goToCard(currentCard); }; const previousCard = function() { if (currentCard === 0) currentCard = lastCard - 1; else currentCard--; goToCard(currentCard); }; btnLeft.addEventListener("click", previousCard); btnRight.addEventListener("click", nextCard);
.slider { display: flex; align-items: center; justify-content: center; position: relative; } .card { position: absolute; top: 6rem; height: 10rem; width: 10rem; display: flex; flex-direction: column; justify-content: space-between; background-color: #634133; transition: all 1s; } .slider__btn { font-size: 3.25rem; color: #fff; background-color: #634133; font-family: sans-serif; border: none; border-radius: 100%; box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.1); position: absolute; top: 50%; z-index: 10; height: 5.5rem; width: 5.5rem; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2 ease; } .slider__btn--left { left: 15%; transform: translate(-50%, 150%); } .slider__btn--right { right: 15%; transform: translate(50%, 140%); } .slider__btn:hover { background-color: rgba(216, 123, 91, 0.85); } .photo__photo { height: 23rem; } .photo__photo--1 { background-color: yellow; } .photo__photo--2 { background-color: red; } .photo__photo--3 { background-color: purple; } .photo__photo--4 { background-color: green; } .photo__photo--5 { background-color: blue; }
<div class="slider"> <div class="card"> <div class="photo photo__photo--1"> </div> </div> <div class="card"> <div class="photo photo__photo--2"> </div> </div> <div class="card"> <div class="photo photo__photo--3"> </div> </div> <div class="card"> <div class="photo photo__photo--4"> </div> </div> <div class="card"> <div class="photo photo__photo--5"> </div> </div> <button class="slider__btn slider__btn--left">←</button> <button class="slider__btn slider__btn--right">→</button> </div>
由于您要手动定位卡片*,只需将间隙乘以索引添加到每个变换值即可。
我还通过使用
:nth-child()
而不是每张幻灯片的单独类来简化您的标记,只是作为建议。* 大多数滑块不这样做。它增加了通常不需要的复杂性。