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

标签 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>

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

最佳答案

除了初始化 html 文档之外,您不能将 document.write 用于任何其他用途。

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

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

关于javascript - 我应该如何在我的代码中使用 setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084114/

相关文章:

css - Firefox 3 和 Safari 不加载 CSS 的某些部分

angularjs - 自定义模态面板大小 Ui Bootstrap

css - 如何编写 Safari(5) 特定的 CSS?

javascript - 继承方法调用触发 Typescript 编译器错误

javascript - 在不是用户本地时区的时区中显示日期

javascript - 如何保存 slider jQuery UI 的更改值

javascript - CSS:在 Firefox 的放大打印预览中,事情变得四处移动

Javascript,固定一位小数,除了为 0 时

Javascript - 数组 - 将一个数组中的值分配给另一个数组中的字符串

javascript - 单击后禁用 CSS 链接 1 秒