我应该如何在我的代码中使用setInterval()

时间:2017-07-13 14:47:21

标签: javascript css

/*Declare each backgroundColor value for each divs*/
var RR;
var GG;
var BB;
/*Declare the numbers of divs for making boxes*/
var y_end = 70;
var x_end = 70;
/*Declare the position*/
var x;
var y;
/*the time now*/
var now = new Date();
/*CSS*/

document.write("<style>");

for (y = 1; y <= y_end; y++) {
  for (x = 1; x <= x_end; x++) {
    if (x < 6) RR = "0" + (x * 3).toString(16);
    else RR = (x * 3).toString(16);

    if (y < 6) GG = "0" + (y * 3).toString(16);
    else GG = (y * 3).toString(16);


    BB = (4 * now.getSeconds()).toString(16);
    if (now.getSeconds() < 4) BB = "0" + (4 * now.getSeconds()).toString(16);

    var hex = "#" + GG + BB + RR;

    document.write(" .r" + x + "g" + y + "{ margin:0; padding:0;width:1vw; height:0.5vh; background-color:" + hex + "; }");

  }
}

document.write("</style>");


/*makes divs for cubes*/
document.write("<div id='cube' style='display:block'>");
for (y = 1; y <= y_end; y++) {

  document.write("<div style='display:table-cell;'>");

  for (x = 1; x <= x_end; x++) {
    document.write("<div class='r" + x + "g" + y + "'></div>");
  }
  document.write("</div>");
}
<script src="cube.js"></script>

我正在制作一个每一秒都有变化的颜色方块。 但我找不到我应该在我的代码中放置setInterval()的位置。 首先,我只在/ CSS /使用它,但它不起作用。还有一堆错误来了。

1 个答案:

答案 0 :(得分:0)

除初始化html文档外,您无法使用document.write。

如果要使用setInterval更改CSS值,可以使用dom操作,例如:

setInterval(function(){
    var div = document.getElementById("mydiv");
    div.style.background-color = "rgb(155, 102, 102)"; 
},1000);
相关问题