这是我第一次真正深入 JavaScript。当然我以前用过它,但我从来没有真正从头开始写过任何东西。
无论如何,我遇到了一个非常奇怪的问题,希望有人能帮我解决。
我正在尝试使 div 中的文本从黑色淡化为白色。很简单吧?
以下代码有效。它会将颜色更改为白色,但是会忽略 500 毫秒的 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);
}
}