每當我單擊瀏覽器上的按鈕時,它都會顯示隨機顏色及其 rgb(r,g,b) 代碼。我制作了 3 個變數r, g, 并使用基本邏輯b產生亂數;0255Math.floor(Math.random()*256)
我的問題是有時生成的隨機顏色太暗,并且與它們一起顯示的 rgb 代碼是黑色的。
我嘗試撰寫一個邏輯,每當 r g b < 300 時,切換具有白色屬性的 h1 元素的類。
const h1 = document.querySelector('h1');
const button = document.querySelector("button");
h1.classList.add('h1');
//if (r g b < 500)
button.addEventListener('click', () => {
changeColor();
});
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
}
);
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
})
uj5u.com熱心網友回復:
一個簡單的方法是使 r、g、b 變數具有更寬的范圍,以便它們可以用于在您更改背景顏色的同一位置進行 <500 測驗。
const h1 = document.querySelector('h1');
const button = document.querySelector("button");
let r, g, b;
h1.classList.add('h1');
button.addEventListener('click', () => {
changeColor();
});
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
if (r g b < 500) h1.style.color = 'white';
else h1.style.color = 'black';
h1.innerText = newColor;
});
const randomColor = (() => {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
})
<h1></h1>
<button>click me</button>
uj5u.com熱心網友回復:
好吧,您必須將 if 放入此函式 (randomColor) 中,并且當為 (r,g,b) 生成值時,您是否會在每次值更改時再次檢查新值。
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
if(r g b < 300){
h1.classList.add('h1');
}
return `rgb(${r}, ${g}, ${b})`;
})
uj5u.com熱心網友回復:
試試這個:
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor[1];
h1.innerText = newColor[1];
const sumColor = newColor[0];
if (sumColor < 300){
h1.style.color = white;
}else{
h1.style.color = black;
}
}
);
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const sum = r g b;
return [sum,`rgb(${r}, ${g}, ${b})`]; //returning array
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463780.html
標籤:javascript 随机的 颜色 RGB
上一篇:eslint不檢測解構變數
