使用 while 循环实现 JavaScript 延迟
该网站位于此处 我正在尝试通过在用户访问时使用 Javascript 移动背景的位置来创建一个动画按钮单击按钮。但是,按钮不是缓慢滚动,而是跳到循环末尾。这是代码:
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;
}
++x;
//reset increasing timer
z=1;
}
}
请让我知道如何修复。谢谢!
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;
}
++x;
//reset increasing timer
z=1;
}
}
Please let me know how to fix. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有效:
DEMO
不知道它是否是最好的不过。
注意:您要么必须在
body.onload
事件处理程序中运行代码,要么将其放在页面底部。您还可以尝试调整步长和超时时间......
还有一些我想说的,但我忘了;)另一个注意事项:您应该始终使用富有表现力的变量名称。例如,尚不清楚
x
是否用作布尔指示器(至少如果您仅快速锁定它)。This works:
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).setTimeout
函数不会暂停,它只是安排在指定的延迟后执行函数(其第一个参数),然后立即返回。因此,启动一大堆超时并没有多大用处。您希望setTimeout
回调调用setTimeout
来启动另一个计时器。您可以使用函数而不是字符串作为setTimeout
的第一个参数。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 thesetTimeout
callback to callsetTimeout
to start another timer. And you can use a function rather than a string as the first argument tosetTimeout
.