我正在做一個簡單的專案,每當我單擊瀏覽器上的按鈕時,它都會顯示隨機顏色及其 rgb(r,g,b) 代碼,我制作了 3 個變數 r,g & b ,它們從 0 產生亂數使用 Math.floor(Math.random()*256) 的基本邏輯到 255;
現在的問題是,有時生成的隨機顏色很暗,并且與它們一起顯示的 rgb 代碼是黑色的,我嘗試撰寫一個邏輯,每當 r g b < 300 時,切換具有屬性的 h1 元素的類白顏色。
我無法配置它;這是我的js代碼:
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熱心網友回復:
您可以繼續生成新顏色,直到亮??度不會太暗,如this answer中建議的那樣:
const COLOR_PARAGRAPH = document.getElementById("color");
const randomColorNotToDark = () => {
do {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var luma = 0.2126 * r 0.7152 * g 0.0722 * b; // from https://stackoverflow.com/a/12043228/6328256
} while (luma < 40);
const newColor = `rgb(${r}, ${g}, ${b})`;
COLOR_PARAGRAPH.innerHTML = newColor;
setBackgroundColor(newColor);
return;
}
const setBackgroundColor = (color) => {
document.body.style.backgroundColor = color;
}
* {
font-family: sans-serif;
}
#content {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
body {
transition: all 0.3s ease;
}
<!DOCTYPE html>
<html>
<body>
<div id=content>
<input type="button" value="Randomize Color" onClick="randomColorNotToDark()">
<p id="color">rgb(0, 0, 0)</p>
</div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463772.html
標籤:javascript html css if 语句
上一篇:顯示不同年份的兩個日期之間的月份
