效果如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: #ffffff;
cursor: default;
}
.ball{
position: absolute;
opacity: 1;
}
</style>
</head>
<body>
<script>
var colorArr = ['#5500ff', '#ff0000', '#00aaff', '#aa007f', '#ff0000', '#0055ff'];
var ballArr=[];
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都是零
// 初始化
this.init();
// 把自己推入数组,注意,这里的this不是类本身,而是实例
ballArr.push(this);
}
var texts=["富强","民主","文明","和谐","自由","平等","公正","法治","爱国","敬业","诚信","友善"];
// 获取随机数
var rand=0;
var timer;
Ball.prototype.init=function(){
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+13+'px';
this.dom.style.top=this.y+4+'px';
this.dom.style.color=this.color;
this.dom.innerText=texts[rand];
rand++;
if(rand>=11){
rand=0;
}
//上树
document.body.appendChild(this.dom);
}
// 更新
Ball.prototype.update = function () {
// 位置改变
this.x += this.dX;
this.y -= this.dY;
// 半径改变
this.r += 0.2;
// 透明度改变
this.opacity -= 0.2;
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 timer;
document.onclick=function(e){
clearInterval(timer);
var x=e.clientX;
var y=e.clientY;
new Ball(x,y);
timer = setInterval(function(){
for(var i=0;i<ballArr.length;i++){
ballArr[i].update();
}
},200)
}
</script>
</body>
</html>
总结:
自己删自己: document.body.removeChild(this.dom);
要注意上下文指的哪个对象。