这是我第一次真正接触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);
}
}
潇潇雨雨
凤凰求蛊
波斯汪
相关分类