我有一个" 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";
});
答案 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
})