利用JS随机生成颜色

html 复制代码
​
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
</head>
<body>
  <div style='height:100px ; width:100px;background-color:"pink"  '></div>
  <!-- /* <div style="height: 100px;"></div> */ -->
  <script>
    alert(Math.floor('a'))
    // 换成Number形式,取整,取得都是原本类型的。${}去掉""
    let arr1={
      red:'red',
      yellow:'yellow',
      blue:'blue',
      black:'black',
      pink:'pink',
      a1:'rgba(1,2,3,0.8)'
    }
    //变量可以写在下面。()
    let arr=['red','yellow','green','blue','black','pink','a1']
    function Random(){
      return Math.floor(Math.random()*arr.length)
    }
    // arr1[arr[Random()]]
    
   let c=arr1[arr[6]]
   console.log(typeof c)
   
  
    document.write(`<div style='height:100px ; width:100px;background-color:${c} '></div>`)
  </script>
  <!-- 需要加; -->
</body>
</html>

​

我写的这个随机生成,其实最后生成的颜色,最后还是看自己写在数组内的颜色。并不能随机生成16进制/rgb任意的。这个随机颜色生成不写这个JSON对象都可以。写不写一样。以及我们在数组当中/对象当中最后取到的是数据类型整个字面值。1是NUmber数据类型,取到整个1,字符串String类型也是整个String。带""表述这个字面值。但是我们反引号取变量,对于字符串放进来会去引号。以及Math.floor这个是把里面的数会转成数字类型,里面有转成数字类型代码。然后再取整。

随机生成颜色,可以对这个#后面六个数随机取/rgb()内部三个数随机取。

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    
    let arr=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']
    if(flag=false){
    let r=Math.floor(Math.random()*256)
    let g=Math.floor(Math.random()*256)
    let b=Math.floor(Math.random()*256)
    document.write(`rgb(${r},${g},${b})`)
    }else{
      let new1='#'
      for(let i=0;i<6;i++){
// 对于#ffffff这种不能像上面这种只用随机数,随机数只是数字,但是这个十六进制有字母,所以只能用
// 数组。但是对于上面的,rgb()内部几个字母。我们知道document内输出的时候,反引号内,随便放,最后得到结果输出。
// 我们输出document.write输出把标签有css一定是字符串类型。引号内写这些颜色。反引号可以写这些变量。
        let c=Math.floor(Math.random()*arr.length)
        new1+=arr[c]
      }
      document.write(new1)
    }

  </script>
</body>
</html>

${}生成的会去字符最后在浏览器上的只有html和css,html不会有JS,但是如果遇到属性值没写双引号会自动加,给的html

相关推荐
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
怕浪猫1 小时前
Electron 开发实战(一):从零入门核心基础与环境搭建
前端·electron·ai编程
杜子不疼.2 小时前
【C++ AI 大模型接入 SDK】 - DeepSeek 模型接入(上)
开发语言·c++·chatgpt
加号32 小时前
【C#】 串口通信技术深度解析及实现
开发语言·c#
小鹏linux2 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
sycmancia2 小时前
Qt——编辑交互功能的实现
开发语言·qt
石山代码3 小时前
C++ 内存分区 堆区
java·开发语言·c++
前端若水3 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Bigger3 小时前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
无风听海3 小时前
C# 隐式转换深度解析
java·开发语言·c#