我这里有一个代码,其中imgNumb的值由timeElapsed变量定义。随着时间的推移imgNumb的值从0开始变为最大4,之后我希望它再次从0开始;喜欢在循环中。完成大部分工作的功能是autoFade()。
问题:问题是在我声明elapsedTime等于延迟后,它仅在剩余的持续时间内保持为4并且不像以前那样增加。
请帮帮我!如果可以的话,我真的很感激!感谢。
以下是代码:
var a = document.getElementById("slidermain");
var b = a.getElementsByTagName("IMG");
var len = b.length;
var cusOpac = 0;
var delay = 4;
var imgNumb = 0;
var elem;
var now, before = new Date();
function autoFade(){
var loop = setInterval(function(){
now = new Date();
var timeDiff = (now.getTime() - before.getTime());
var elapsedTime = Math.floor(timeDiff/1000);
var lendelay = len*delay;
var currentFrame = Math.floor(elapsedTime/delay)-1;
var imgNumb = currentFrame % 5;
initFade(imgNumb);
}, delay*1000);
}
function initFade(imgNumb){
elem = b[imgNumb];
startFadeEffect(elem);
}
function startFadeEffect(elem){
opacSetting = cusOpac / 10;
elem.style.opacity = opacSetting;
elem.style.display = "block";
cusOpac++;
if(cusOpac > 10){
cusOpac = 10;
}
var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
if(opacSetting == 1){
clearTimeout(timer);
cusOpac = 10;
elem.style.opacity = 1;
setTimeout(function() { endFadeEffect(elem); }, (delay*1000)/2);
}
}
function endFadeEffect(elem){
opacSetting = cusOpac / 10;
elem.style.opacity = opacSetting;
cusOpac--;
if(cusOpac < 0){
cusOpac = 0;
}
var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
if(opacSetting == 0){
clearTimeout(timer);
elem.style.opacity = 0;
elem.style.display = "none";
cusOpac = 0;
return false;
}
}
请注意我正在寻找仅限javascript的解决方案!
答案 0 :(得分:0)
请正确格式化代码并尝试将其减少到必要的绝对最小值。在你的情况下,我相信你要求创建一个函数f(elapsedTimeSeconds)
- &gt; imgNumb
,就像这样:
delay * 0 <= elapsedTimeSeconds < delay * 1
,imgNumb
= 0 delay * 1 <= elapsedTimeSeconds < delay * 2
,imgNumb
= 0 delay * 2 <= elapsedTimeSeconds < delay * 3
,imgNumb
= 1 delay * 3 <= elapsedTimeSeconds < delay * 4
,imgNumb
= 2 delay * 4 <= elapsedTimeSeconds < delay * 5
,imgNumb
= 3 delay * 5 <= elapsedTimeSeconds < delay * 6
,imgNumb
= 4 delay * 6 <= elapsedTimeSeconds < delay * 7
,imgNumb
= 0 delay * 7 <= elapsedTimeSeconds < delay * 8
,imgNumb
= 1 ......等等。
您已经发现Math.floor(elapsedTimeSeconds/delay)-1
可以为您提供delay*1 <= elapsedTimeSeconds < delay*6
所需的内容,但之后会继续增长。
所以你需要的是一个产生:
的函数..等等。这是modulo operation:
var currentFrame = Math.floor(elapsedTimeSeconds/delay)-1;
var imgNumb = currentFrame % 5;