我仍在努力使用我简单的JavaScript游戏。这是我之前的问题:Simple javascript game, hide / show random square
一些方形显示并隐藏了几秒钟,你必须点击它们。我使用RaphaelJS绘制正方形和一些JQuery($ .each()函数)
我不能使用setInterval为每个方块设置hide / show。 Mishelle的功能看起来不错,但是我得到了一个“这不是一个函数”的错误。我测试了不同的东西,但它没有我想象的那么明显:/
window.onload = function() {
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
// random function to for the x and y axis of the square
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var rectanglemain = paper.rect(0, 0, 500, 500).attr({fill: "white",});
var win_click = 0; // set the var to count the click on the square
var recs = [];
for(var i = 0; i < 50; i++) {
var x = random(1,450);
var y = random(1,450);
var rec = paper.rect(x, y, 50, 50).attr({fill: 'blue'});
recs.push(rec); // add the square in an array
recs[i].click(function () {
//counting the clicks
win_click = win_click + 1;
})
function hideSquare() {recs[i].hide();}
hideSquare();
}
rectanglemain.click(function () {
alert('you click on ' + win_click + ' squares');
});
/* here is a function made by Mishelle on my previous question, unfortunately I can't make it work (this is not a function error).
function showBriefly (timeFromNow, duration) {
window.setTimeout(this.rec.show, timeFromNow);
window.setTimeout(this.rec.hide, timeFromNow + duration);
}
recs[2].showBriefly(1000, 3000); to test the function
*/
}
感谢您的帮助:)
答案 0 :(得分:0)
尝试
window.setTimeout(function(){this.rec.show();}, timeFromNow )
答案 1 :(得分:0)
刚刚遇到了您的问题,以防您在阅读本文时想知道问题是什么。回调中this
为undefined
,因此您需要在变量中存储您引用的矩形(我称之为square
),请参阅我的代码:
showBriefly: function(timeFromNow, duration) {
square = this.box;
setTimeout(function(){square.show();}, timeFromNow )
setTimeout(function(){square.hide();}, timeFromNow + duration )
}
干杯