[英]How to change the body's background color with buttons using javascript?
[英]How to change body background color within a Javascript function
我正在嘗試在 Raspberry Pi 網站 ( https://projects.raspberrypi.org/en/projects/cd-beginner-javascript-sushi/8 ) 上進行 Guess the Color 練習的挑戰部分。
挑戰要求我將身體背景顏色更改為游戲中的獲勝顏色,在游戲中您會看到頂部的 RGB 顏色代碼和下方的 6 個彩色圓圈。 您必須通過單擊每一個來猜測 6 個彩色圓圈中的哪個具有呈現的 RGB 顏色代碼,程序會告訴您正確和不正確。
選擇正確的圓圈后,主體背景顏色應更改為正確圓圈的顏色,這就是我遇到問題的地方。 我認為我的代碼是正確的,但我認為問題涉及某些變量的局部性,而不是考慮到這一點。
有問題的區域是我的 script.js 文檔中的第 40-50 行; 還有一些我用來排除故障的注釋行。 document.body.style.backgroundColor 行確實有效,但對 setButtonColour 的 function 調用以及 setAttribute function 不起作用。
問題是document.getElementsByTagName('body');
返回<body>
元素的列表。
您應該將此行更改為var winning = document.getElementsByTagName('body')[0];
訪問第一個(也是唯一的) <body>
元素。
如果你想引用 javascript 中的<body>
,你應該使用document.body
。
文檔:
您的代碼中的第 46 行似乎有錯誤:
winning.setAttribute('style','background-color: rgb('+ red +','+ green +','+ blue +');');
看看行尾 - 你不應該使用;
在background-color
之后+');');
document.getElementById('btn').addEventListener('click',function(){ document.body.style.backgroundColor = 'red'; });
<button id="btn">Change body color</button>
您正在生成 colors 而不保存正確答案。
if (i === answerButton) {
heading.innerHTML = 'R:' + red + ' G:' + green + ' B:' + blue;
//add this ->
winnerRed = red;
winnerGreen = green;
winnerBlue = blue;
}
你用這個來稱呼它:
document.body.style.backgroundColor = "rgb("+ winnerRed +","+ winnerGreen +","+ winnerBlue + ")";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.