JS:我怎样才能使用生成的随机数并将其设置为div的背景颜色

时间:2017-03-18 15:58:58

标签: javascript css

我有一个" var rgb"为div中的每次单击生成RGB颜色。现在我想将它作为背景颜色随机地应用到div#div;#game"中的一个。我该怎么办?

的index.html

<header>
  <p class="great">xxx</p>
  <p id="rgb">RGB(143, 80, 16)</p>
  <p class="great">xxxx</p>
</header>

<nav>
  <div id="game">
    <div id="newColors">NEW COLORS</div>
    <div id="result">RESULT</div>
    <div id="easy"><span>EASY</span> <span>HARD</span></div>
  </div>
</nav>


  <div id="game">
    <div class="firstSquare"></div>
    <div class="secondSquare"></div>
    <div class="thirdquare"></div>



    <div class="firstSquare"></div>
    <div class="secondSquare"></div>
    <div class="thirdquare"></div>
  </div>

的script.js

  var r = Math.floor(Math.random() * 255);
  var g = Math.floor(Math.random() * 255);
  var b = Math.floor(Math.random() * 255);
  var rgb = "RGB(" + r + "," + g + "," + b + ")";

  var colorRGB = document.getElementById("rgb");
  var headerRGB = document.getElementById("newColors");
  var squareOne = document.getElementById("one");

  headerRGB.addEventListener("click", function() {
     colorRGB.textContent = rgb;
     squareOne.style.backgroundColor = "rgb";
  });

1 个答案:

答案 0 :(得分:1)

rgb是一个变量,而不是一个字符串。你不小心把它放在引号中。尝试:

squareOne.style.backgroundColor = rgb

此外,如果要在每次单击时生成新的随机颜色,请将随机化逻辑放在事件侦听器中:

 var colorRGB = document.getElementById("rgb")
 var headerRGB = document.getElementById("newColors")
 var game = document.getElementById("game")

 headerRGB.addEventListener("click", function() {
   var r = Math.floor(Math.random() * 255)
   var g = Math.floor(Math.random() * 255)
   var b = Math.floor(Math.random() * 255)
   var rgb = "RGB(" + r + "," + g + "," + b + ")"

   colorRGB.textContent = rgb
   var div = game.children[Math.floor(Math.random() * game.children.length)]
   div.style.backgroundColor = rgb
 })