JS变色药丸

 今天我们来做一个JS变色药丸,每次刷新网页随机变色

原理:

  1. 药丸的两部分分别采用16进制颜色编码和rgb颜色编码
  2. 创建两种编码的数组
  3. 利用Math.floor(Math.random() * color_arr.length)抽取数组随机元素
  4. 再利用模版字符串将盒子写入DOM。

效果如下:

代码如下:

<!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>
<style>
  div {
    width: 100px;
    height: 100px;
    margin: 0 auto;
  }

  div:nth-of-type(1) {
    border-radius: 50% 50% 0 0;
  }

  div:nth-of-type(2) {
    border-radius: 0 0 50% 50%;
  }
</style>

<body>
  <script>
    // 1.获取16进制颜色编码函数
    createColor_16 = function () {
      let color_arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']
      sum = '#'
      for (let i = 0; i < 6; i++) {
        randomNum = Math.floor(Math.random() * color_arr.length)
        sum += color_arr[randomNum]
      }
      return sum
    }

    // 2.获取rgb颜色编码函数
    createColor_rgb = function () {
      let numArr = []
      for (let i = 0; i < 3; i++) {
        getNum = Math.floor(Math.random() * 256)
        // 储存生成数组
        numArr.push(getNum)
      }
      console.log(numArr)
      return `rgb(${numArr[0]}, ${numArr[1]}, ${numArr[2]})`
    }

    // 颜色渲染16进制颜色盒子
    document.write(`
    <div style = "background-color: ${createColor_16()};"></div>
    `)

    // 颜色渲染16进制颜色盒子
    document.write(`
    <div style = "background-color: ${createColor_rgb()};"></div>
    `)

  </script>
</body>

</html>
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值