css生成随机颜色

编辑 (opens new window)
上次更新: 2025/04/18, 01:42:12
Maoyl's blog 
<html>
<div id="btn" class="btn">请点击我</div>
</html>
<script>
let timeoutRef;
//使用
function $(el){
return document.querySelector(el)
}
$('#btn').onclick = function () {
timeoutRef && clearInterval(timeoutRef);
document.getElementById('btn').style.backgroundColor = createRandomColor();
document.getElementById('btn').style.border = `5px solid ${createRandomColor() }`;
}
function createRandomColor(){
return `#${Math.random().toString(16).slice(-6)}`
}
timeoutRef = setInterval(() => {
document.getElementById('btn').style.backgroundColor = createRandomColor();
document.getElementById('btn').style.border = `6px solid ${createRandomColor()}`;
}, 300)
</script>
<style>
.btn {
display: flex;
align-items: center;
justify-content: center;
border: 6px solid green;
width: 100%;
height: 200px;
font-size: 25px;
font-weight: bold;
color: #000000;
background-color: blue;
}
</style>