随机产生一个十六进制的颜色值,封装成一个函数,进行调用!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
div {
position: absolute;
top: 0;
left: 0;
width: 100%;
min-height: 100%;
height: auto;
background-color: coral;
text-align: center;
}
div strong {
display: block;
font-size: 30px;
padding-top: 20%;
}
</style>
</head>
<body>
<div><strong>点击随机切换颜色</strong></div>
<script>
function changeBgColor() {
var str = "#";
var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
for (var i = 0; i < 6; i++) {
var result = parseInt(Math.random() * 16);
str += arr[result];
}
return str;
}
var div = document.querySelector('div');
div.onclick = function() {
div.style.backgroundColor = changeBgColor();
}
</script>
</body>
</html>