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