JavaScript 如何实现从数组中随机选取一个颜色作为类的某个属性值?

例如有一组 RGBA 颜色值:

rgb(144,144,255),rgba(255,78,106,.15),rgba(255,118,30,.15),rgba(255,185,0,.15),rgba(0,219,255,.15),rgba(51,213,122,.15),rgba(0,219,255,.15)

需要实现以下效果,但希望文字( color )或背景颜色(background-color)是从列表中随机选取的:

img

btn {
margin: 5px;
border-radius: 13px;
padding: 5px 10px;
font-size: 12px;
background:想要随机的颜色;
display: inline-block;
}

希望对你有所帮助~

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p>啊啊啊啊</p>

    <script>
        let p = document.querySelector('p');
        let colors = ["rgb(144,144,255)", "rgba(255,78,106,.15)", "rgba(255,118,30,.15)", "rgba(255,185,0,.15)", "rgba(0,219,255,.15)", "rgba(51,213,122,.15)", "rgba(0,219,255,.15)"]
        p.style.color = colors[Math.floor(Math.random() * colors.length)]  
    </script>
</body>

</html>
  1. 色值用一个数组存起来
  2. 随机获取这个数组里的色值
  3. 更改元素的背景/文字颜色

示例:

  <body>
    <div class="btn" onclick="onChangeColor()">
      <p>按钮</p>
    </div>
    <script>
      const colorArr = ['rgb(144,144,255)', 'rgba(255,78,106,.15)', 'rgba(255,118,30,.15)', 'rgba(255,185,0,.15)', 'rgba(0,219,255,.15)', 'rgba(51,213,122,.15)', 'rgba(0,219,255,.15)'];

      const div = document.querySelector('.btn');
      const text = document.querySelector('.btn p');

      function onChangeColor() {
        div.style.backgroundColor = colorArr[parseInt(Math.random() * colorArr.length)];
        text.style.color = colorArr[parseInt(Math.random() * colorArr.length)];
      }
    </script>
  </body>