<!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>
<style>
.father {
display: flex;
}
p {
width: 27%;
height: 100px;
border: 1px solid white;
text-align: center;
}
</style>
</head>
<body>
<div class="father">
<p>第一个P</p>
<p>第二个P</p>
<p>第三个P</p>
<p>第四个P</p>
</div>
<button id="btn">点击按钮窗口颜色将变化</button>
<script>
// 1、 获取元素,绑定事件
var Btn = document.getElementById("btn");
var op = document.getElementsByTagName("p");
Btn.onclick = function () {
for (var i = 0; i < op.length; i++) {
op[i].style.background = Rgb(); // 每个 p 标签背景色,随机
}
}
// 封装一个函数,函数返回 rgb()随机颜色
function Rgb() {
// agb(num1,num2,num3); 三个参数随机获取
var num1 = parseInt(Math.random() * 256);
//console.log(num1);
var num2 = parseInt(Math.random() * 256);
//console.log(num2);
var num3 = parseInt(Math.random() * 256);
//console.log(num3);
//console.log("rgb"+"("+num1+","+num2+","+num3+")");
return "rgb" + "(" + num1 + "," + num2 + "," + num3 + ")";
}
</script>
</body>
</html>