用面向对象实现简易双色球
html部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
p{
margin-left: 20px;
}
</style>
<body>
<div class="qq"></div>
<div class="aa"></div>
<script src="./index.js"></script>
</body>
</html>
js部分:
//获取随机数
function getNum(min, max = 0) {
min > max ? [min, max] = [max, min] : "";
return parseInt(Math.random() * (max - min + 1)) + min;
}
let qqEle = document.getElementsByClassName("qq")[0]
let aaEle = document.getElementsByClassName("aa")[0]
class Shu {
render() {
qqEle.innerHTML = ""
let str = new Set();
while (str.size < 6) {
str.add(getNum(1, 33));
}
let arr = [...str];
for (let index of arr) {
new Qiu(100, "red", index)
}
new Qiu(100, "skyblue", getNum(1, 15))
}
}
let stu = new Shu()
// 球
class Qiu {
constructor(width, bgc, number) {
this.width = width;
this.bgc = bgc;
this.number = number;
this.node = document.createElement("p");
this.render();
}
itin() {
Object.assign(this.node.style, {
width: this.width + "px",
height: this.width + "px",
color: "white",
fontSize: "30px",
backgroundColor: this.bgc,
display: "flex",
justifyContent: "center",
alignItems: "center",
borderRadius: "50%"
})
this.node.innerHTML = this.number;
qqEle.appendChild(this.node)
}
render() {
this.itin();
}
}
let time;
function init() {
qqEle.style.display = "flex";
qqEle.style.left = "10px"
}
init();
//创建按钮类
class CreateBtn {
constructor({
type,
value,
}) {
this.node = document.createElement(`input`);
this.type = type;
this.value = value;
//整合节点属性
Object.assign(this.node, {
type: this.type,
value: this.value
});
}
}
//主函数类
class BaoPo {
render() {
this.init();
}
init() {
//实例化按钮
let btn1 = new CreateBtn({
type: "button",
value: "开始",
});
let btn2 = new CreateBtn({
type: "button",
value: "结束",
});
//把实例化的按钮添加到页面
aaEle.appendChild(btn1.node);
aaEle.appendChild(btn2.node);
btn1.node.addEventListener("click", function () {
time = setInterval(stu.render, 10);
btn1.node.disabled = true
btn2.node.removeAttribute("disabled")
});
btn2.node.addEventListener("click", function () {
clearInterval(time)
btn2.node.disabled = true
btn1.node.removeAttribute("disabled")
});
}
}
let BP = new BaoPo();
BP.render();