JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Js随机颜色的几种方法

2020. 08. 04    

JS随机颜色的几种方法

<script>
  var getRandomColor = function () {
    return '#' +
      (function (color) {
        return (color += '0123456789abcdef'[Math.floor(Math.random() * 16)])
          && (color.length == 6) ? color : arguments.callee(color);
      })('');
  }
  // 方法二
  // var getRandomColor = function () {
  //   return (function (m, s, c) {
  //     return (c ? arguments.callee(m, s, c - 1) : '#') +
  //       s[m.floor(m.random() * 16)]
  //   })(Math, '0123456789abcdef', 5)
  // }
  // 方法三
  // var getRandomColor = function () {
  //   return '#' + '0123456789abcdef'.split('').map(function (v, i, a) {
  //     return i > 5 ? null : a[Math.floor(Math.random() * 16)]
  //   }).join('');
  // }
  // 方法四
  // var getRandomColor = function () {
  //   return '#' + (Math.random() * 0xffffff << 0).toString(16);
  // }
  // 方法五 浅色   
  // var getRandomColor = function () {
  //   return '#'
  //     + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
  // }
  // 方法六   
  // function getRandomColor() {
  //   var r = Math.floor(Math.random() * 256);
  //   var g = Math.floor(Math.random() * 256);
  //   var b = Math.floor(Math.random() * 256);
  //   return "rgba(" + r + ',' + g + ',' + b + ',' + 0.2 + ")"; //所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`
  // }
  document.querySelector('p').style.color = getRandomColor()
  console.log(getRandomColor())
</script>