我有一個「var rgb」,它爲div中的每次點擊生成RGB顏色。現在我想隨機將它作爲背景顏色應用於其中一個div的「#遊戲」中。我該怎麼做?JS:我如何使用生成的隨機數並將其設置爲div的背景色
的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";
});
'el.style.backgroundColor =「RGB(0 ,0,0)';' –
你有rgb的引號,你爲什麼要將文本顏色設置爲與bg相同? –