首页 > 解决方案 > Javascript not operating on loaded elements

问题描述

I am trying to understand grid layouts so I wrote some js to recursively color each element on the page to expose each grid tile.

The problem

Every few refreshes some of the tiles don't get colored. I figured this was some kind of loading error so instead of running the code immediately I decided to run it in window.onload. That didn't change anything.

I even wrote a piece of code to print the uncolored elements to the console. I run that code in the same loop where individual elements are painted and expected nothing to be logged, to my surprise the color is generated, the element is created, and still the element remains uncolored!

Plea

Can someone tell me what's going on here? It's not very important in this application but this goes against everything I know about how js operates, and it would be helpful to extend my understanding. Thanks!

P.S. Demo

I added this little demo and the problem happens here too. You will need to run the code a couple times to see the error, I wrote another piece of code that prints the uncolored element to the console so you can't miss it!

let colorize = (elements) => {
  for (let e of elements) {
    let color = '#' + Math.floor(Math.random() * 16777215).toString(16);
    e.style["background-color"] = color;
    checkcolor(e, color);
    colorize(e.children);
  }
}
let checkcolor = (e, color) => {
  if (!e.style['background-color']) {
    console.log(e, color);
  }
}
window.onload = () => colorize(document.querySelector("html").children);
body {
  height: calc(100vh - 3px);
  display: grid;
  grid-template-rows: repeat(5, minmax(10px, 100px));
  /* grid-template-columns: 1; */
  grid-auto-flow: row;
}
<div>11</div>
<div>22</div>
<div>33</div>
<div>44</div>
<div>55</div>

标签: javascripthtmlcss

解决方案


以下是其中一个结果的示例console.log

<div>55</div> #43b0f

这应该给你的想法 - 生成的字符串只有 5 个字符(或更少),而不是 6 个,所以它不是有效的十六进制颜色。当生成的数字具有前导零时,就会发生这种情况。

解决它的一种方法是padStart使用零的数字:

const colorize = (elements) => {
  for (let e of elements) {
    let color = '#' +
      Math.floor(Math.random() * 16777215)
      .toString(16)
      .padStart(6, '0');
    e.style["background-color"] = color;
    colorize(e.children);
  }
}
colorize(document.querySelectorAll('div'));
body {
  height: calc(100vh - 3px);
  display: grid;
  grid-template-rows: repeat(5, minmax(10px, 100px));
  /* grid-template-columns: 1; */
  grid-auto-flow: row;
}
<div>11</div>
<div>22</div>
<div>33</div>
<div>44</div>
<div>55</div>


推荐阅读