gpt4 book ai didi

javascript - 为什么我的 slider 脚本中有些元素未定义?

转载 作者:行者123 更新时间:2023-11-30 08:24:53 24 4
gpt4 key购买 nike

我正在为 JavaScript 创建图像 slider 。我有它,以便我的左右箭头显示下一张图像。我想添加一个 setInterval 方法来每隔几秒更改一次显示图像。我假设它会像调用函数一样简单,每 3 秒单击一次正确的图像。但是我收到一条错误消息

index.js:26 Uncaught TypeError: Cannot read property 'style' of undefined
at slideRight (index.js:26)

这是我的代码

let sliderImages = document.querySelectorAll('.slide');
let arrowLeft = document.getElementById('arrow-left');
let arrowRight = document.getElementById('arrow-right');
let current = 0;

function reset() {
for(let i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = 'none';
}
}

function startSlider() {
reset();
sliderImages[0].style.display = 'block';
}

function slideLeft() {
reset();
sliderImages[current - 1].style.display = 'block';
current --;
}


function slideRight() {
reset();
sliderImages[current + 1].style.display = 'block';
console.log(current);
current ++;
console.log(current);
}

arrowLeft.addEventListener('click', function() {
reset()
if(current == 0) {
current = sliderImages.length;
}
slideLeft();
});

arrowRight.addEventListener('click', function () {
if(current == sliderImages.length -1 ) {
current = -1;
}

slideRight();
})
startSlider();

setInterval(slideRight, 3000);

最佳答案

在我看来,您的问题是,当您向右走得太远时,索引不再存在于数组中,因此您需要在向右走时使用模数运算符:

sliderImages[(current + 1) % sliderImages.length].style.display = 'block';

当向左走得太远时,您需要绕到右侧:

sliderImages[current - 1 >= 0 ? 
current - 1 : sliderImages.length - 1].style.display = 'block';

关于javascript - 为什么我的 slider 脚本中有些元素未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47401250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com