面向对象的本质:定义不同的类,让类的实例工作
面向对象的应用场景:需要封装和复用性的场合(组件)
<!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>彩球案例</title>
<style>
body {
background: #000;
}
.ball {
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<script>
// 小球类
function Ball(x,y) {
// 属性x\y为圆心坐标
this.x = x
this.y = y
// 半径属性
this.r = 20
// 透明度
this.opacity = 1
// 小球背景色,从颜色数组中随机选择一个
this.color = colorArr[parseInt(Math.random() * colorArr.length)]
// x和y的增量
// 通过 do...while语句,防止dX和dY都是零时不动的情况
do{
this.dX = parseInt(Math.random() * 20) - 10
this.dY = parseInt(Math.random() * 20) - 10
}while(this.dX == 0 && this.dY == 0)
// 调用自己的初始化方法
this.init()
// 把自己放入数组,此时this指向实例,而不是类本身
ballArr.push(this)
}
// 初始化方法
Ball.prototype.init = function() {
// 创建自己的DOM
this.dom = document.createElement('div')
this.dom.className = 'ball'
this.dom.style.width = this.r * 2 + 'px'
this.dom.style.height = this.r * 2 + 'px'
this.dom.style.left = this.x - this.r + 'px'
this.dom.style.top = this.y - this.r + 'px'
this.dom.style.backgroundColor = this.color
// 上树
document.body.appendChild(this.dom)
}
// update方法
Ball.prototype.update = function () {
// 改变位置
this.x += this.dX
this.y -= this.dY
// 改变半径
this.r += 0.2
// 改变透明度
this.opacity -= 0.01
this.dom.style.width = this.r * 2 + 'px'
this.dom.style.height = this.r * 2 + 'px'
this.dom.style.left = this.x - this.r + 'px'
this.dom.style.top = this.y - this.r + 'px'
this.dom.style.opacity = this.opacity
// 当透明度为0时,需要从数组中删除自己,对应的DOM也需要删除
if(this.opacity < 0) {
// 从数组中删除自己
for(var i = 0;i < ballArr.length;i++) {
if(ballArr[i] == this) {
ballArr.splice(i,1)
}
}
// 删除DOM
document.body.removeChild(this.dom)
}
}
// 把所有小球实例放入数组
var ballArr = []
// 初始颜色数组
var colorArr = ['#66cccc','#ccff66','#ff99cc','#ff6666','#cc3399','#ff6600']
// 定时器,负责更新所有的小球实例
setInterval(() => {
// 遍历数组,调用小球的update方法
for(var i = 0;i < ballArr.length;i++) {
ballArr[i].update()
}
}, 20);
// 鼠标监听
document.onmousemove = function(e) {
// 得到鼠标的位置
var x = e.clientX
var y =e.clientY
// 实例化
new Ball(x,y)
}
</script>
</body>
</html>