我正在尝试使用javascript创建一个简单的滑块。 到目前为止,这是我的代码:
html:
<div class="carousel-container">
<div class="slides-container">
<div class="slide">
<img src="assets/images/image-1.jpg" alt="">
</div>
<div class="slide">
<img src="assets/images/image-3.jpg" alt="">
</div>
<div class="slide">
<img src="assets/images/image-2.jpg" alt="">
</div>
<div class="slide">
<img src="assets/images/image-3.jpg" alt="">
</div>
</div>
</div>
<div class="carousel-nav">
<button class="button-previous">Previous</button>
<button class="button-next">Next</button>
</div>
Js:
const slides = document.querySelectorAll('.slide')
const slidesContainer = document.querySelector('.slides-container')
const slidesCount = slides.length
const slideWidth = slides[0].clientWidth
const prevButton = document.querySelector('.button-previous')
const nextButton = document.querySelector('.button-next')
function nextSlide(slide) {
for (slide = 0; slide < slidesCount; slide++) {
slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
}
}
nextButton.addEventListener('click', function() {
nextSlide()
})
我遇到的问题是,当我单击下一个按钮时,滑块会一直移到数组的末尾,从而跳过了中间的所有图像。
让我的for循环在每个图像处停止并在单击按钮时再次出现的最佳方法是什么?
答案 0 :(得分:0)
let current = 0;
function nextSlide(slide) {
if (current < slidesCount) {
slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)';
current++;
}
}
答案 1 :(得分:0)
每次单击都跳到结尾的原因是:for()
循环。您正在循环浏览幻灯片的所有-每次点击 都会生成一次新的translateX
坐标。每次都给您留下最后的价值。
给出的答案CheapGamer定义了一种模式,可以通过跟踪for()
处理程序的当前“滑动”索引 outside 来避免nextSlide()
循环陷阱
let current = 0; // <- independent index reference
function nextSlide(slide) {
if (current < slidesCount) {
slidesContainer.style.transform = 'translateX(-' + (current * slideWidth) + 'px)';
current++; // <- increment the index
}
}
// I changed the `slide` reference in `(slide * slideWidth)` to `current` to reflect the intent of the code
这将使您通过轮播增加,直到current
等于3
。 (slide
中的nextSlide(slide)
参数不是必需的。)
答案 2 :(得分:0)
我可能不太清楚您要做什么或为什么要使用for循环,但是如果只是选择下一张幻灯片,您可以这样做:
var currentSlide = 0;
function nextSlide() {
//make sure currentSlide is in range
currentSlide = (currentSlide >= slidesCount) ? 0 : ++currentSlide;
slidesContainer.style.transform = 'translateX(-' + (currentSlide * slideWidth) + 'px)';
}
nextButton.addEventListener('click', nextSlide);
或更灵活一点:
var currentSlide = 0;
function nextSlide(direction /* Number */) {
if(!direction) direction = 1; //default
setSlide(currentSlide + direction % slidesCount);
}
function setSlide(index) {
if(index === currentSlide) return;
//make sure index is in range
while(index >= slidesCount) index -= slidesCount;
while(index < 0) index += slidesCount;
slidesContainer.style.transform = 'translateX(-' + (index * slideWidth) + 'px)';
currentSlide = index;
}
nextButton.addEventListener('click', function() {
nextSlide(this.dataset["direction"]); //by using data you don't need two different button classes
});
但是,如果您坚持使用循环,恐怕很难告诉您这种情况是不合适的,因为translateX的计算基于给定值。