请老师检查下代码

来源:6-2 上升到面向对象-炫彩小球小案例

不厌_

2021-06-20 19:46:54

浏览器不开检查运行时正常,开了检查(控制台打开body元素)后移动就会越来越卡顿,不知道是不是电脑老旧性能问题?

测试了老师的示例代码也是这样。

相关代码:

​<!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>Document</title>
<style>
body {
background-color: black;
}

.ball {
position: absolute;
border-radius: 50%;
width: 88px;
}
</style>
</head>

<body>
<script>
// 球类有颜色、半径大小、坐标、随机移动量属性 + 初始化方法和更新方法
function Ball(x, y) {
this.x = x;
this.y = y;
this.r = 20;
this.color = colorArr[parseInt(Math.random() * colorArr.length)];
this.opacity = 1
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');
document.body.appendChild(this.dom);
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;
}
// 更新方法,更新位置,半径大小,透明度
Ball.prototype.update = function () {
this.x += this.dx;
this.y -= this.dy;
this.r += 0.1;
this.opacity -= 0.02;
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,就删除自身
if (this.opacity <= 0) {
// dom中删除自己
document.body.removeChild(this.dom);
// 数组中删除自身
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);
};
}

}
};
var ballArr = [];
var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666', '#CC3399', '#FF6600'];
// 给鼠标添加事件监听,移动就会出现小球
document.onmousemove = function (e) {
var x = e.clientX;
var y = e.clientY;
new Ball(x, y);
};
// 定时器每20毫秒就遍历球类数组,调用小球的更新方法
setInterval(function () {
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update();
}
}, 20);

</script>
</body>

</html>


写回答

1回答

好帮手慕星星

2021-06-21

同学你好,代码实现效果可以。

老师打开控制台测试卡顿并不明显,可以多换几个浏览器试试。掌握了原理,知道怎么实现就好。

祝学习愉快!

0

前端工程师

前端入门如同写字,如果你不知道从哪开始,那就选择前端(含Vue3.x,React17,TS)

20327 学习 · 17877 问题

查看课程