有人能告诉我为什么这段代码不会在两种颜色之间闪现我网页的背景颜色吗?
<script type="text/javascript">
function blinkit() {
intrvl = 0;
for (nTimes = 0; nTimes < 3; nTimes++) {
intrvl += 1000;
setTimeout("document.bgColor='#0000FF';", intrvl);
intrvl += 1000;
setTimeout("document.bgColor='#FFFFFF';", intrvl);
}
}
</script>发布于 2013-02-28 20:23:38
试试这个:
function blinkit() {
intrvl = 0;
window.setInterval(function(){
intrvl += 1000;
setTimeout("document.bgColor='#0000FF';", intrvl);
intrvl += 1000;
setTimeout("document.bgColor='#FFFFFF';", intrvl);
}, intrvl);
}发布于 2013-02-28 20:31:56
不要将字符串传递给setTimeout,因为它与eval一样糟糕。
相反,可以尝试这样的方法:
function blinkit(times, thenwhat) {
var toggle = times*2, timer = setInterval(function() {
document.body.style.backgroundColor = toggle%2 ? "#0000FF" : "#FFFFFF";
toggle--;
if( !toggle) {
clearInterval(timer);
thenwhat && thenwhat();
}
},1000);
return timer;
}
var flashy = blinkit(3);
// The background will flash three times.
// You can also cancel it with `clearInterval(flashy);`使用上面的代码,您还可以让它在完成时做一些事情:
var flashy = blinkit(3,function() {alert("Hello!");});https://stackoverflow.com/questions/15144522
复制相似问题