【发布时间】:2022-11-02 03:05:12
【问题描述】:
我将不胜感激任何帮助。每次按钮的背景颜色较深时,我都想更改按钮的文本颜色。我一直在尝试以下代码的其他变体。我似乎无法让 newColor 工作。在此先感谢您的帮助。
const button = document.querySelector('button');
const h1 = document.querySelector('h1');
button.addEventListener('click', () => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
})
let newColor;
const randomColor = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
newColor = r * 0.299 + g * 0.587 + b * 0.114
if(newColor > 186) {
newColor = 'black';
} else {
newColor = 'white';
}
return `rgb(${r}, ${g}, ${b})`;
}
我尝试制作自己的函数,我尝试在函数外部放置一个 if 语句。
【问题讨论】:
标签: javascript dom