问题遇到的现象和发生背景
为什么删掉
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);
}
这段话就得不到DOM节点了
问题相关代码,请勿粘贴截图
<script>
function Ball(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 {
this.dX = parseInt(Math.random() * 20) - 10;
this.dY = parseInt(Math.random() * 20) - 10;
} while (this.dX == 0 && this.dY == 0)
// 初始化
this.init();
ballArr.push(this);
}
// 初始化方法
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 - this.r + 'px';
this.dom.style.top = this.y - this.r + 'px';
this.dom.style.backgroundColor = this.color;
document.body.appendChild(this.dom);
};
// 更新
Ball.prototype.update = function () {
// 位置改变
this.x += this.dX;
this.y -= this.dY;
this.dom.style.left = this.x - this.r + 'px';
this.dom.style.top = this.y - this.r + 'px';
// 透明度改变
this.opacity -= 0.01;
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);
}
}//如果删了就会报错
document.body.removeChild(this.dom);
}
};
var ballArr = [];
// 初始颜色数组
var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666',
'#CC3399', '#FF6600'];
setInterval(function () {
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>
运行结果及报错内容
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
我的解答思路和尝试过的方法
我想不通,为什么这段话会影响删除节点?
我想要达到的结果
如果我不不放入数组遍历小球,能否让document.body.removeChild(self.dom);不报错?
Ball.prototype.update = function () {
var self = this;
setInterval(function () {
self.x += self.dx;
self.y += self.dy;
self.dom.style.left = self.x - self.r + 'px';
self.dom.style.top = self.y - self.r + 'px';
self.opacity -= 0.01;
self.dom.style.opacity = self.opacity;
document.body.removeChild(self.dom);
}, 20);
};