利用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

相关推荐
蓝星空20004 分钟前
GPT Image 2.5 生图模型已上线,支持 Flare 与 Sunburst 型号选择
前端·gpt·aigc·image2·imagen
小溪学编程5 分钟前
Java ListIterator 接口详解:双向遍历与列表修改的利器
java·开发语言·windows
影视飓风TIM6 分钟前
C++11 新特性:Lambda表达式、std::function与std::bind
开发语言·c++
sbjdhjd10 分钟前
在 8 字符、字母数字过滤与 PHP 版本差异下复盘临时文件命令执行链 | (8字符绕过)
android·java·开发语言·安全·web安全·数据挖掘·php
何何____16 分钟前
js常见继承方法详解
前端·javascript
parade岁月21 分钟前
Tailwind CSS 加入 Shopify,正在用 Tailwind 的项目要不要调整?
前端
梨想橙汁34 分钟前
Vue2 快速入门:环境搭建、模板语法、指令系统全解
前端·vue.js
King of fraud38 分钟前
HTML 页面的 CSS 选择器详解
前端·css·html
lichenyang45340 分钟前
ASCF 元服务如何区分“后台恢复”与“携参拉起”:后台标记 + 参数指纹方案
前端
前端 贾公子40 分钟前
Milvus使用指南 (下)
java·服务器·前端