例如有一组 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)是从列表中随机选取的:
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>
示例:
<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>