2016-06-12 64 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

相關問題