繁体   English   中英

通过 javascript 将随机 rgb 背景颜色分配给 HTML 主体

[英]Assign a random rgb background color to HTML body via javascript

标题说明了大部分内容。 我想向一个按钮添加一个事件,该按钮在单击时更改正文的背景。 查看我的代码:

document.querySelector("button").addEventListener("click", function(){
    var randomColors = [];
    var rgbString = "rgb(";
    for(var i = 0; i <= 2; i++){
        randomColors[i] = Math.floor(Math.random() * (255 + 1));
        if(i < 2){
            rgbString += randomColors[i].toString() + ",";
        }else{
            rgbString += randomColors[i].toString() + ")";
        }
    }
    document.body.style.background = "\"" + rgbString + "\"";
});

我在这个问题上挣扎了太久。 由于console.log("\"" + rgbString + "\"")返回一个正确的字符串,例如。 "rgb(0,55,103)"我无法找出错误。

非常感谢!

document.body.style.background = "\"" + rgbString + "\""中删除"\"""\"" ""

 document.querySelector("button").addEventListener("click", function(){ var randomColors = []; var rgbString = "rgb("; for(var i = 0; i <= 2; i++){ randomColors[i] = Math.floor(Math.random() * (255 + 1)); if(i < 2){ rgbString += randomColors[i].toString() + ","; }else{ rgbString += randomColors[i].toString() + ")"; } } console.log(rgbString) document.body.style.background = rgbString });
 <button> button </button>

这是我找到的最短答案

 document.querySelector("button").addEventListener("click", function(){ var randomColors = []; var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; randomColors.push(hue); console.log(hue); document.body.style.background = hue; });
 <button>change color</button>

根据@Roys 的回答,您需要删除"\"" and "\""并且您也可以使用以下逻辑

ES6

您可以创建一个具有随机 rgb 颜色值的function并使用new Array(3).fill('').map()来实现结果


 const random=() => Math.floor(Math.random() * (255 + 1)); document.querySelector("button").addEventListener("click", ()=>{ document.body.style.background = `rgb(${new Array(3).fill('').map(v=>random()).join(',')})` });
 <button>Change color</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM