the site is here I'm trying to create an animated button by moving the position of the background using Javascript when the user clicks the button. However, instead of slowly scrolling, the button jumps to the end of the loop. Here's the code:
var x=1, y=0, z=1;
function animate () {
document.getElementById("switch").style.backgroundPosition = y + 'px 0px';
}
function toggle() {
// check if button is on
if (x==1) {
//As long as image is not yet in place, move the background
while (y>-37) {
//Delay each move by 500 and increase the delay
setTimeout("animate()",500*z);
--y;++z;
}
--x;
//reset increasing timer
z=1;
}
// check if button is off
else if (x==0) {
//As long as image is not yet in place, move the background
while (y<0) {
//Delay each move by 500 and increase the delay
setTimeout("animate()",500*z);
++y;++z;
开发者_如何学Go }
++x;
//reset increasing timer
z=1;
}
}
Please let me know how to fix. Thanks!
This works:
var on = true,
sw = document.getElementById("switch"),
stop, y = 0,
dir, to;
function animate() {
sw.style.backgroundPosition = y + 'px 0px';
y += dir;
if (y != stop) {
to = setTimeout(animate,25);
}
}
function toggle() {
if (to) {
clearTimeout(to);
}
if (on) {
dir = -1;
stop = -38;
}
else {
dir = 1;
stop = 2;
}
to = setTimeout(animate, 25);
on = !on;
}
DEMO
Don't know if it is the best way though.
Note: You either have to run the code in the body.onload
event handler or put it at the bottom of the page.
You can also try to play with the step size and the timeout time.... there was something else I wanted to say, but I forgot ;)
Another note: You should always use expressive variable names. E.g. It was not clear that x
is used as a boolean indicator (at least not if you only have a quick lock at it).
The setTimeout
function doesn't pause, it just arranges to execute the function (its first argument) after the specified delay and then immediately returns. So, launching a whole bunch of timeouts isn't that useful. You want the setTimeout
callback to call setTimeout
to start another timer. And you can use a function rather than a string as the first argument to setTimeout
.
精彩评论