0

尝试在我的 while 循环中使用动画运行我的函数,在该动画中我移动方块,我只希望它运行一次。不要让它工作。如果我使用 setInterval 它只会动画多次。而我现在拥有它的方式根本没有动画。这就是它现在的样子。欣赏一些提示。谢谢!

编辑 - 根据计数 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
}
?>
4

2 回答 2

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>
于 2013-10-18T08:26:45.537 回答
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>
于 2013-10-18T09:05:45.063 回答