【问题标题】:How to change background color randomly in a javascript function如何在javascript函数中随机更改背景颜色
【发布时间】: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


    【解决方案1】:

    您可以使用以下代码:

    document.getElementById("button").onclick = () => {
      var randomColor = Math.floor(Math.random()*16777215).toString(16);
      console.log(randomColor)
      document.getElementById("button").style.backgroundColor = `#${randomColor}`
    }
    

    如有任何疑问,请写信给我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 2015-06-23
      • 2013-10-14
      相关资源
      最近更新 更多