2013-10-18 60 views
0

試圖在我的while循環中運行我的函數,並在其中移動方塊的動畫,我只希望它運行一次。不要讓它工作。如果我使用setInterval,它只會動畫多次。我現在怎麼擁有動畫呢?這是它現在的樣子。欣賞一些提示。謝謝!運行函數一次(在一個while循環中)

編輯 - 正方形根據計數ID動畫到不同的位置。

<?php 
... 
$count = 0; 
while($rows = mysql_fetch_array($data)){ //many rows 
$count = $count + 1 
    $id= $rows['id']; //different id's for each row 


?> 
<script> 
    var ID = '<?php echo $id; ?>'; 
      var count = '<?php echo $count; ?>';  
</script> 

<div id="squares" style="height:50px; width:50px; position:relative; background:black;" > 

<script> 
    document.getElementById('squares').id = ID; //make div id "squares" to ID 

//So here the it doesn't work. 
function(){ 
    if(count == 1){ 
    $('#' + ID).animate({left: (700), top: (300)}, 2000); 
    $('#' + ID).animate({left: (300), top: (500)}, 2000); 
    } 
    if(count == 2){ 
    $('#' + ID).animate({left: (100), top: (400)}, 2000); 
    $('#' + ID).animate({left: (100), top: (800)}, 2000); 
    } 
} 

</script> 
<?php 
} 
?> 
+0

「的setInterval」 =>循環VS「setTimeout的」 =>等待和運行一次 – pbenard

+0

首先,你應該分開HTML,CSS, JavaScript和PHP。不要把所有東西放在同一個文件中,因爲這樣只會讓你編碼湯。 – str

+1

如果你只想讓它運行一次,爲什麼你要在循環中調用一個函數? – feeela

回答

0
<html> 
<head> 
<script> 

    $(document).ready(function() { 
     // NOTE: I suspect what you want to do is run one animation after the other, 
     // you need a callback function for that. 
     $('.toBeAnimated1').animate({ left: (700), top: (300) }, 2000, function() { 
      $('.toBeAnimated1').animate({ left: (300), top: (500) }, 2000); 
     }); 
     $('.toBeAnimated2').animate({ left: (100), top: (400) }, 2000, function() { 
      $('.toBeAnimated2').animate({ left: (100), top: (800) }, 2000); 
     }); 
    }); 

</script> 
</head> 
<body> 
<?php 
... 
$count = 0; 
while($rows = mysql_fetch_array($data)){ //many rows 
$count = $count + 1 
    $id= $rows['id']; //different id's for each row 
    ?> 
    <div id="<? echo $id; ?>" class="toBeAnimated<? echo $count; ?>" style="height:50px; width:50px; position:relative; background:black;" > 
<? 
} 
?> 
</body> 
</html> 
+0

顯然有更好的方法。您可能需要考慮在數據庫中保存方格的值(開始位置,結束位置等)​​,以便使其更通用。 – CompanyDroneFromSector7G

0

我能看到的第一件事是在PHP while循環中,您正在編寫一堆JS腳本,每個腳本處理單個元素的動畫。你應該更改到一個JS腳本,動畫所有元素:

<?php 
...  
while($rows = mysql_fetch_array($data)){ //many rows 
    $id= $rows['id']; //different id's for each row 
    $left = $rows['left']; // <---- replace this with your logic for determining top and left 
    $top = $rows['top']; 
?> 

<div id="<?php echo $id; ?>" class="square" style="height:50px; width:50px; position:relative; background:black;" data-animateLeft="<?php echo $left; ?>" data-animateTop="<?php echo $top; ?>"> 

<?php 
} 
?> 

<script> 
$('.square').each(function(){ 
    $this = $(this); 
    $this.animate({left: +$this.data('animateLeft'), top: +$this.data('animateTop')}, 2000); 
}); 
</script> 
+0

看到你的觀點。但是每個廣場都將被動畫到不同的位置。如果我能從中獲得好處,我會保留! :) @Tibos – PeterP

+0

@Alex Goransson查看此編輯。你也可以用JS中的數據結構來保存每個項目的座標,但是我認爲它更像這樣的語義。 – Tibos