【发布时间】:2018-11-01 20:00:37
【问题描述】:
我刚刚开始学习 javascript 中的 OOP,我正在尝试使用 OOP 重新编写一个简单的程序,该程序之前编写为过程程序。该程序是一个反应测试器,其中屏幕上出现一个随机形状,用户必须尽快单击它。单击形状后,将显示用户响应所需的时间(以秒为单位)。
我还没有走多远,我只是想让一个随机大小和随机颜色的正方形出现在屏幕上,但我什至无法做到。请参阅下面的代码:
<script type="text/javascript">
function Shape () {
this.x = Math.floor(Math.random()*850);
this.y = Math.floor(Math.random()*850);
this.draw();
}
Shape.prototype.draw = function() {
var shapeHtml = '<div></div>';
var widthAndHeight = Math.floor(Math.random()*400);
var left = Math.floor(Math.random()*850);
var top = Math.floor(Math.random()*850);
this.shapeElement = $(shapeHtml);
this.shapeElement.css({
position: "relative",
left: this.left,
top: this.top,
width: widthAndHeight,
height: widthAndHeight,
});
$("body").append(this.shapeElement);
}
Shape.prototype.colour = function() {
var colours = '0123456789ABCDEF'.split('');
var randomColour = "#";
for (i = 0; i < 6; i++) {
randomColour+=colours[Math.floor(Math.random()*16)];
};
this.shapeElement.css({backgroundColor: 'randomColour'});
}
var square = new Shape();
</script
到目前为止,屏幕上不会出现任何方块。所发生的只是附加了一个随机大小的 div,但它始终位于左上角并且没有背景颜色。控制台没有帮助我,因为它没有显示我的代码中有任何错误。我非常困惑,发现向 OOP 的过渡非常令人困惑。非常感谢任何有助于理解为什么这不起作用的帮助!
【问题讨论】:
-
如果你想“绘图”,
canvas元素非常简洁:developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial -
position: 'absolute'和backgroundColor: randomColor是您想要的。你也应该在某个地方打电话给colour()。投票以 typo 结束 -
对不起,应该是
backgroundColor: randomColour,重点是你应该使用变量randomColour而不是字符串文字'randomColour' -
我更改了代码以反映 Phil 的最后评论,但它完全没有任何区别。
标签: javascript jquery oop