老师关于炫彩小球一些疑问
这是老师源代码
<!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: black;
}
.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);
};
// 更新
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(function () {
// 遍历数组,调用调用的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>
下面这个地方为什么还要用if语句来判断下,直接移除掉不就好了嘛因为他透明度已经小于0了啊
// 从数组中删除自己
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);
}
}
// 这个地方直接写就好了啊
ballArr.splice(i, 1);
16
收起
正在回答 回答被采纳积分+1
1回答
好帮手慕慕子
2021-04-07 17:55:38
同学你好,对于你的问题解答如下:
1、不可以直接写ballArr.splice(i,1),因为不加判断的话,无法知道从数组中删除是不是当前实例化的小球,而当使用splice方法删除数组的元素时,会改变原来的数组,并不是按着原来的for循环依次删除里面的元素,导致效果实现存在误差,所以需要添加判断,只删除自己即可。
2、透明度已经小于0,页面中确实看不见了,不删除也是可以的,但是这样的话页面中会有越来越多看不见的dom元素,当你移动鼠标的时候,这些看不见的小球依然会通过js计算来改变样式,影响浏览器性能,可能会造成页面卡顿,所以推荐将看不见的小球删除了。
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星