js随机色背景图

tech2025-03-22  5

Yes,i’m here

也不知道写点啥,就来写个随机的颜色吧

现在写个div,然后设置他的宽高,加个边框看看咋样。 emmm~,还不错,继续写。 我要写的是十六进制的颜色,大家应该知道,十六进制的颜色开头都是#(井号),里面不是数字就是字母,那咱就开整。

function color(){ //井号放在开头拼接 let colorStr = "#"; //十六进制里字母最大到F数字最大到9 let str = "ABCDEF123456789"; //看到for循环和我前面提到的拼接,大家应该猜到我要干什么了吧 for(let i = 0; i < 6; i++;){ //Math.floor表示向下取整 Math.random表示随机数0(包含)~1(不包含) str.length是str的长度 //整体就是str的下标为 随机的数字乘str的长度(最小是0最大是14) //然后每次循环加在colorStr后面一个 colorStr += str[Math.floor(Math.random() * str.length)] } //再把colorStr return 出去 ruturn colorStr } //获取到id选择器名字为color的标签,样式中背景色(backgroundColor为驼峰写法)为color(),方法执行后就会把return出的colorStr赋给背景色 document.getelementById('color').style.backgroundColor = color()

就是这样↓ 整体代码↓

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div{ width: 100px; height:100px; border: 1px solid black; } </style> </head> <body> <div id="color"></div> <script> function color(){ let colorStr = '#' let str = 'ABCDEF123456789' for (let i = 0; i < 6; i++) { colorStr += str[Math.floor(Math.random() * str.length)] } console.log(colorStr) return colorStr } document.getElementById('color').style.backgroundColor = color() </script> </body> </html>

妙啊(awesome) 各位再见~~~

最新回复(0)