我是編碼初學者(如果這個問題有一個容易解決的解決方案,請原諒我),但我正在嘗試創建一個顏色翻轉器,每次在“生成”按鈕時將網頁的背景更改為隨機顏色被點擊。我不知道如何配置按鈕,所以我查看了一個關于如何配置的教程。教程和我的版本的代碼是一樣的,但是我在網頁上點擊了一次“生成”后,就再也沒有改變背景了。下面是按鈕的代碼:
<main>
<div class="container">
<h1>color flipper</h1>
<h2>press the button to generate a random color.</h2>
<h3> color: <span class="color">#000000</span></h3>
<button class="btn btn-hero" id="btn">generate</button>
</div>
</main>
<script>
const btn = document.getElementById("btn")
const color = document.querySelector(".color")
let a = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
let c = Math.floor(Math.random() * 256)
let colors = `rgb(${a}, ${b}, ${c})`
btn.addEventListener('click', () => {
document.body.style.backgroundColor = colors
color.textContent = colors
})
</script>
uj5u.com熱心網友回復:
隨機顏色始終相同,您需要重新生成它們:
const btn = document.getElementById("btn")
const color = document.querySelector(".color")
function generate() {
let a = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
let c = Math.floor(Math.random() * 256)
let colors = `rgb(${a}, ${b}, ${c})`
document.body.style.backgroundColor = colors
color.textContent = colors
}
btn.addEventListener('click', () => {
generate()
})
<main>
<div class="container">
<h1>color flipper</h1>
<h2>press the button to generate a random color.</h2>
<h3> color: <span class="color">#000000</span></h3>
<button class="btn btn-hero" id="btn">generate</button>
</div>
</main>
uj5u.com熱心網友回復:
每當btn點擊時,您需要確保每次都生成新顏色。您可以通過將顏色生成邏輯置于事件偵聽器的回呼中來實作此目的。
const btn = document.getElementById("btn")
const color = document.querySelector(".color")
btn.addEventListener('click', () => {
let a = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
let c = Math.floor(Math.random() * 256)
let colors = `rgb(${a}, ${b}, ${c})`
document.body.style.backgroundColor = colors
color.textContent = colors
})
<main>
<div class="container">
<h1>color flipper</h1>
<h2>press the button to generate a random color.</h2>
<h3> color: <span class="color">#000000</span></h3>
<button class="btn btn-hero" id="btn">generate</button>
</div>
</main>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402224.html
標籤:javascript html css 按钮
