我想将div的背景颜色更改一秒钟,然后将其恢复为原始颜色。我正在制作一个西蒙游戏,无法弄清楚如何在一段时间内闪现一种颜色。到目前为止我有这个:
var red = document.getElementById("redBox");
flashRed();
function flashRed() {
red.style.background = "#ff0000"; //light red "flash" color
wait(800);
red.style.background = "#a80000"; //normal red color
}
function wait(ms) {
var time = new Date();
var millisecs = time.getTime();
var startTime = millisecs;
var currentTime = millisecs;
while(currentTime - startTime < ms) {
time = new Date();
currentTime = time.getTime();
}
}
如何将亮红色闪烁800毫秒,然后将颜色恢复为红色?
你应该使用setTimeout()函数。例如,它会在选定的时间后触发一些回调
setTimeout(function(){
// some code
},1000); // for 1s = 1000ms
您可以在setTimeout函数中添加类,以便您的CSS可以更改背景。
这是一个有效的例子:fiddle here
简而言之,首先你的元素需要一些初始样式,当你想要改变颜色或其他东西时,你只需添加另一个具有一些属性的类 - 在这个例子中是红色backgorund,但同时你设置超时以便稍后删除它但不是停止你的整个代码。
< script type = "text/javascript" >
toggle_color("#61beb3", "#90a2c6", 4000, 2000);
function toggle_color(color1, color2, cycle_time, wait_time) {
setInterval(function first_color() {
document.body.style.backgroundColor = color1;
setTimeout(change_color, wait_time);
}, cycle_time);
function change_color() {
document.body.style.backgroundColor = color2;
}
} < /script>
上面的Javascript代码只需每2秒切换一次HTML正文的背景颜色。你应该使用setTimeout()函数。它会在选定的时间后触发一些回调。颜色#61beb3将保留为背景,直到#90a2c6被change_color()函数设置为背景。
这不是解决这个问题的方法。而是通过setTimeout()
使用计时器:
var div = document.querySelector("div");
var originalColor = getComputedStyle(div).backgroundColor; // Store original color (red)
div.style.backgroundColor = "#ff0"; // Change color
// Set a timer to run the passed function after 1000 milliseconds (1 second)
setTimeout(function(){
div.style.backgroundColor = originalColor; // Change the color back to the original
}, 1000);
div {
width:50px;
height:50px;
background-color:red; /* This is the original color */
}
<div></div>