创建一个类
<!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>
.circle {
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<header>
<button id="addcircle"> 添加小球</button>
</header>
<div class="content" id="content"></div>
<script>
// 获取盒子
const content = document.getElementById('content')
console.log('***', content)
const addcircle = document.getElementById('addcircle') //获取按钮对象
class Circle {
constructor(props = {}) {
const {
r = this.random(20, 50),
color = this.randomColor(), //#cccc
x = 50,
y = 50
} = props;
this.r = r;
this.color = color;
this.x = x;
this.y = y;
this.createEl(); //创建dom节点
} // 创建dom
createEl() {
const { color, r, x, y } = this;
this.circle = document.createElement('div');
this.circle.className = 'circle';
this.circle.style.width = `${r * 2}px`;
this.circle.style.height = `${r * 2}px`;
this.circle.style.background = `${color}`;
this.circle.style.left = `${x}px`;
this.circle.style.top = `${y}px`;
content.appendChild(this.circle);
}
//生成随机数
random(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
//生成颜色的方法
randomColor(mix, max) {
// #cccccc
const letters = ['a', 'b', 'c', 'd', 'e', 'f']
const strs = [...letters]
for (let i = 0; i < 10; i++) {
strs.push(i);
}
console.log(strs);
let colorStr = '#';
let i = 0;
while (i < 6) {
let index = this.random(0, strs.length);
colorStr += strs[index];
i++;
}
return colorStr;
}
}
addcircle.onclick = () => {
new Circle()
console.log(Circle)
}
// const c1 = new Circle();
// const c2 = new Circle({
// color: 'blue',
// x: 400,
// y: 50
// })
</script>
</body>
</html>