[英]How can i make my image carousal loop in vanilla javascript?
I have created a simple image carousal but I would like it to go back to the start when the final slide item is reached so it appears to have a loop我创建了一个简单的图像轮播,但我希望 go 在到达最终幻灯片项目时回到开始,因此它似乎有一个循环
My HTML:我的 HTML:
<div class="slider" id="slider">
<img class="slide" src="/assets/image-slide-1.jpg" alt="">
<img class="slide" src="/assets/image-slide-2.jpg" alt="">
<img class="slide" src="/assets/image-slide-3.jpg" alt="">
<img class="slide" src="/assets/image-slide-4.jpg" alt="">
<img class="slide" src="/assets/image-slide-5.jpg" alt="">
</div>
<div class="buttons">
<button id="prev">
<img src="/assets/icon-arrow-left.svg" alt="">
</button>
<button id="next">
<img src="/assets/icon-arrow-right.svg" alt="">
</button>
My JavaScript:我的 JavaScript:
const slidesContainer = document.getElementById("slider");
const slide = document.querySelector(".slide");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");
nextButton.addEventListener("click", (event) => {
const slideWidth = slide.clientWidth;
slidesContainer.scrollLeft += slideWidth;
});
prevButton.addEventListener("click", () => {
const slideWidth = slide.clientWidth;
slidesContainer.scrollLeft -= slideWidth;
});
If width (height, if slider is vertical) of slider is as long as, say, two images, place copies of last two images to the beginning of slider and whenever user reaches the end of slider move it to the very beginning If width (height, if slider is vertical) of slider is as long as, say, two images, place copies of last two images to the beginning of slider and whenever user reaches the end of slider move it to the very beginning
For the nextButton
event handler function you could add a conditional:对于
nextButton
事件处理程序 function 您可以添加一个条件:
if (slidesContainer.scrollLeft >= slideWidth * 4) {
slidesContainer.scrollLeft = 0;
}
and for the prevButton
you would do the opposite:而对于
prevButton
你会做相反的事情:
if (slidesContainer.scrollLeft <= 0) {
slidesContainer.scrollLeft = scrollWidth * 4;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.