Js code for progressbar, not working
<div><div id="movingbar"></div></div>
var i;
function startTime( i )
{
if ( i < 100 )
{
document.getElementById("movingbar").style.wi开发者_如何学运维dth = i + "%";
t = setTimeout('startTime( i++ )', 1000);
} else return;
}
This should produce something like a progress bar. But the function is executed only once. What is wrong O_o The recursion should not end until i is under 100!?! No errors on FireBug and IE.
Because you're passing a string to timeout which is the code to be evaluated you're actually telling it to run the code 'startTime(i)' and i is undefined at the time that it's run. What you want it to run is 'startTime(2)', 'startTime(3)', etc.
This should work for you:
t = setTimeout('startTime(' + ++i + ')', 1000);
You're passing the string literal i++
to your function. Try using an anonymous function.
function startTime( i )
{
if ( i < 100 )
{
document.getElementById("movingbar").style.width = i + "%";
i++;
t = setTimeout(function() { startTime(i); }, 1000);
} else return;
}
This works:
<div style="height: 20px;"><div id="movingbar" style="height: 20px;background: #000;"></div></div>
window.onload=function(){var i=1;
startTime(i);
}
function startTime( i )
{
if ( i < 100 )
{
document.getElementById("movingbar").style.width = i + "%";
i++;
t = setTimeout('startTime('+i+')', 1000);
} else return;
}
Try it here: http://jsfiddle.net/pHxSy/
精彩评论