所以,我正在尝试用jQuery制作我自己的幻灯片,在我点击所有3张幻灯片后,我想让它在下一次点击后显示第一张图片,或者在我向后点击第一张图片后显示第三张图片,你知道的,就像无限图库。我知道在索引值大于arr.length后,我必须将索引更改为0(如果我想向后返回,则更改为2),但我不知道如何更改。我尝试了无数的if语句,得到的结果都是index停留在2,或者根本不起作用。
<div class="tetusa clearfix">
<div class="slideshow">
<img src="img/muzi_slideshow_1.jpg" id="1" class="active" alt="">
<img src="img/muzi_slideshow_2.jpg" id="2" class="down" alt="">
<img src="img/muzi_slideshow_3.jpg" id="3" class="down" alt="">
</div>
<a class="prev">❮</a>
<a class="next">❯</a>
</div>let prev = $(".prev");
let next = $(".next");
let arr = []
arr[0] = $("#1");
arr[1] = $("#2");
arr[2] = $("#3");
let index = 0;
prev.click(function(){
arr[index-1].removeClass("down");
arr[index-1].addClass("active");
arr[index].addClass("down");
arr[index].removeClass("active");
index --;
});
next.click(function(){
if(index <= arr.length){
arr[index+1].removeClass("down");
arr[index+1].addClass("active");
arr[index].addClass("down");
arr[index].removeClass("active");
}
index ++;
if (index > arr.length) {
index = 0;
}
console.log(index);
});发布于 2021-10-11 17:40:41
你只需要在代码的逻辑上下功夫。您的想法是正确的,但是您需要在if语句之后添加/删除下一张幻灯片的类:
next.click(function(){
arr[index].addClass("down");
arr[index].removeClass("active");
index ++;
if (index === arr.length) {
index = 0;
}
arr[index].removeClass("down");
arr[index].addClass("active");
});希望您知道如何将此逻辑应用于其他侦听器。
发布于 2021-10-11 18:22:19
我认为你可以简化你的代码。将display: none设置为您的所有.slideshow img。然后在你的JavaScript中,每点击一次,检查索引的值是什么,并相应地调整它。它可以通过几行普通的JavaScript来实现。这里是一个示例,请阅读代码中的注释:
/* querySelectorAll enables you to work with any number of slides */
const slides = document.querySelectorAll(".slide")
let index = 0
function prev() {
/* First hide the current slide */
let active = document.querySelector(".active")
active.classList.remove("active")
/* We need to target the previous slide.
If index is 0, set it to the last slide */
index = index > 0 ? index - 1 : slides.length - 1
/* Make it visible */
slides[index].classList.add("active")
}
function next() {
/* First hide the current slide */
let active = document.querySelector(".active")
active.classList.remove("active")
/* We need to target the next slide.
If index is equal to the last element, set it to the first slide */
index = index < slides.length - 1 ? index + 1 : 0
/* Make it visible */
slides[index].classList.add("active")
}.slide {
/* Hide all slides by default */
display: none;
}
.active {
/* Show the active slide */
display: block;
}<button onclick="prev()">Previous</button>
<!-- Show the first slide -->
<div class="slide active">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<button onclick="next()">Next</button>
https://stackoverflow.com/questions/69530092
复制相似问题