2016-06-12 67 views
1

我目前正在制作一个游戏,其中积木掉落,你必须避免它们。我有一些jQuery代码,将块添加到div,名为游戏如何移动一个div的孩子没有任何事件

我无法选择每一个产生的div,并使它们向下移动而没有点击。 Here is the GitHub link这里的example

这里是jQuery代码(一部分)

function spawn_block(){ 

$spawned_block = $("<div class='block'></div>") 
$game.append($spawned_block); //add div with class block to #game div 

var left=getRandomInt(0, $game.width()-$spawned_block.width()); //gets a random value from left of screen where div can appear 
var top=getRandomInt(0, $game.height()-$spawned_block.height()); //not useful unless you don't want the div to appear at the top 
//adds a random position and color to spawned_block 

$spawned_block.css({ 
    "left": left, 
    "background-color": getRandomColor() 
}); 
//if you want a random position from top add "top" : top, 
}; 

if($spawned_block.position.top < $game.position.top + $game.height) { 
     $spawned_block.css("top", "+=25px"); 
    } 

这最后一段代码是我在函数的末尾加上一句,我我做错了?

回答

1

不知道这是发生在你身上的事情,但只是最近添加的div向下移动?也许它会帮助,如果你不喜欢的东西:标识#game的元素中通过每一个.block

$("#game .block").each(function(index){ 
    if($(this).position.top < $game.position.top + $game.height) { 
     $(this).css("top", "+=25px"); 
    } 
}); 

这正好和运行您if声明就可以了。

另一件可能是你的问题(我怕你的问题不够清楚,我可以告诉)是你只运行一个函数来在事件发生时将所有东西都向下移动(比如点击或一个块被添加)。或许,这样的事情可能会为你工作:

function anim() { 
    $("#game .block").each(function(index){ 
     if($(this).position.top < $game.position.top + $game.height) { 
      $(this).css("top", "+=25px"); 
     } 
    }); 
    window.requestAnimationFrame(anim); 
} 
window.requestAnimationFrame(anim); 

这告诉浏览器(通过线window.requestAnimationFrame(anim);),其在下一帧,运行的上下移动的块的功能anim()。你可以阅读更多关于requestAnimationFrame()here

祝你好运!

+0

我很感谢您的帮助,但它仍然不适合我! :(仍然,大thx让我看看我的基本错误 – FlipFloop

+0

@FlipFloop如果你可以更新你的问题或你的GitHub与最新版本的代码,我可以修改我的答案,以更好地帮助你。 – laef

+0

我更新了! thx为你的帮助 – FlipFloop

相关问题