假设我有一个带5张幻灯片的循环轮播。如何使用javascript确定从当前幻灯片到新幻灯片需要较少的步骤(前进或后退)?
即当前在幻灯片3上,并且想要转到幻灯片0。在这种情况下,前进的步骤比返回的步骤少。
(0),1、2,[3],4,(0),1、2等。
香港专业教育学院想出了这一点,但似乎很棘手。我想念一个概念吗?
const targetSlide = 0;
const currentSlide = 3;
const itemCount = 5;
let forwardRange;
let backwardsRange;
if(currentSlide != targetSlide){
for(let i = 0; i < itemCount; i++){
let j = currentSlide + i;
if(j >= itemCount){
j = j - itemCount;
}
if(j == targetSlide){
forwardRange = i;
backwardsRange = itemCount - i;
}
}
if(forwardRange - backwardsRange <= 0){
console.log('go forward')
}else{
console.log('go backward')
}
}
最佳答案
您可以计算前进或后退的成本,并以此来确定方向。
const targetSlide = 0;
const currentSlide = 3;
const itemCount = 5;
const forwardsCost = currentSlide < targetSlide
? targetSlide - currentSlide
: itemCount - currentSlide + targetSlide;
const backwardsCost = currentSlide > targetSlide
? currentSlide - targetSlide
: currentSlide + itemCount - targetSlide;