[英]How do I change the background color using javascript?
我想將背景顏色更改為從數組中隨機選擇的顏色,但我不確定我在做什么。 我對如何使按鈕工作感到困惑。
這是 HTML 的正文,最終我必須將文本更改為它更改為的顏色的名稱,但我想先獲取顏色:
const colors = ['#e5051b', '#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193']; const randomColor = colors[Math.floor(Math.random() * colors.length)]; let button = document.getElementById('button'); button.addEventListener('click', function changeColor() { const color = randomColor; document.body.style.backgroundColor = `${color}`; });
<body> <div class="box"> <div> <p>Hex color code: #ffffff</p> <button class="button">Change Color</button> </div> </div> </body>
每次點擊都必須隨機着色
const colors = ['#e5051b', '#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193']; let button = document.getElementById('button'); button.addEventListener('click', function changeColor() { let randomColor = colors[Math.floor(Math.random() * colors.length)]; document.body.style.backgroundColor = `${randomColor}`; });
<body> <div class="box"> <div> <p>Hex color code: #ffffff</p> <button id="button">Change Color</button> </div> </div> </body>
這是正確的代碼
const colors = ['#e5051b','#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193'];
let button = document.getElementsByClassName('button');
console.log(button);
button[0].addEventListener('click',function changeColor()
{
const color = colors[Math.floor(Math.random()*colors.length)];
console.log(color)
document.body.style.backgroundColor = `${color}`;
});
首先,如評論中所述,您使用了錯誤的元素選擇器。
let button = document.querySelector('.button');
之后,您應該將隨機化代碼放入點擊事件偵聽器中,以便每次點擊按鈕時都會生成隨機顏色
button.addEventListener('click',function changeColor()
{
let random_color = colors[Math.floor(Math.random()*colors.length)];
document.body.style.backgroundColor = `${color}`;
});
你在這里做錯了兩件事。 第一個是,通過 id 獲取DOM
中不存在的元素。 因此,您必須在控制台中收到錯誤消息。 其次,您只是在腳本運行時選擇隨機顏色,而不是每次單擊按鈕時。
因此,您應該做的是,將class="button"
更改為id="button"
或將getElementById
更改為getElementsByClassName[0]
。 要在每次點擊時獲得隨機顏色,您應該移動點擊處理程序內的邏輯以每次運行它並從給定的顏色數組中選擇一個隨機顏色。
const colors = ['#e5051b', '#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193']; const randomColor = colors[Math.floor(Math.random() * colors.length)]; let button = document.getElementById('button'); let p = document.getElementById('color'); button.addEventListener('click', function changeColor() { const randomColor = colors[Math.floor(Math.random() * colors.length)]; const color = randomColor; document.body.style.backgroundColor = `${color}`; p.textContent = `Hex color is ${color}` });
<body> <div class="box"> <div> <p id="color">Hex color is #ffff</p> <button id="button">Change Color</button> </div> </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.