更改div背景颜色一秒钟,然后将其返回到javacsript中的原始颜色 [英] Change div background color for one second then return it to the original color in javacsript

查看:418
本文介绍了更改div背景颜色一秒钟,然后将其返回到javacsript中的原始颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改div的背景颜色一秒钟,然后将其返回原始颜色。我正在制作一个西蒙游戏,并且无法弄清楚如何在一段时间内闪烁颜色。到目前为止,我有这样的:

  var red = document.getElementById(redBox); 

flashRed();

函数flashRed(){
red.style.background =#ff0000; //浅红色闪颜色
等待(800);
red.style.background =#a80000; //正常红色
}

函数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();


$ / code>

我会如何闪烁800ms亮红色然后返回到红色?

解决方案

您应该使用setTimeout()函数。例如

  setTimeout(function(){
//某些代码
},1000); // for 1s = 1000ms

您可以在setTimeout函数中添加类,以便您的CSS可以更改背景。 / p>

下面是一个工作示例:小提琴 总之,首先你的元素需要一些初始样式,当你想要改变颜色或其他的东西时,你只需添加一些具有一些属性的类 - 在本例中是红色的backgorund,但是同时你设置超时时间以便稍后删除它,但不会停止你的整个代码。


I would like to change the background color of a div for one second then return it back to the original color. I am making a Simon game and can't figure out how to flash a color for a period of time. So far I have this:

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();
  }
}

How would I go by flashing the bright red for 800ms and then returning the color back to red?

解决方案

You should use setTimeout() function. It fires some callback after selected time, for example

setTimeout(function(){
     // some code
},1000); // for 1s = 1000ms

You can add class in setTimeout function so your CSS can change background.

Here is working example: fiddle here

In short, first of all your element need some initial styles and when you want to change color or something else you just add another class with some properties - red backgorund in this example but at the same time you set timeout to remove it later but not stopping your whole code.

这篇关于更改div背景颜色一秒钟,然后将其返回到javacsript中的原始颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆