这是我第一次真正接触JavaScript。当然,我曾经使用过它,但是我从未真正写过任何东西。无论如何,我遇到了一个非常奇怪的问题,希望有人可以帮我解决。我正在尝试使div的文本从黑变白。很简单,是吗?以下代码有效。它将颜色更改为白色,但是,忽略了500ms的setTimeout时间。如果您使用Chrome浏览器并查看JS控制台,您将很容易看到doFade()方法几乎是即时调用的,而不是每500毫秒调用一次。谁能解释一下?var started = false;var newColor;var div;var hex = 0;function fadestart(){ if (typeof fadestart.storedColor == 'undefined') { div = document.getElementById('test'); fadestart.storedColor = div.style.color; } if(!started){ console.log('fadestart'); newColor = fadestart.storedColor; started = true; setTimeout(doFade(), 500); }}function fadestop(){ console.log('fadestop'); div.style.color = fadestart.storedColor; started = false; hex = 0;}function doFade(){ if(hex<=238){ console.log(hex); hex+=17; div.style.color="rgb("+hex+","+hex+","+hex+")"; setTimeout(doFade(), 500); }}
3 回答

凤凰求蛊
TA贡献1825条经验 获得超4个赞
setTimeout(doFade(), 500);
这一行说“ execute doFade(),然后将返回的值传递给setTimeout,它将在500毫秒后执行此返回值”。即,您是doFade()在现场打电话。
跳过括号将函数传递给setTimeout:
setTimeout(doFade, 500);
添加回答
举报
0/150
提交
取消