动画不适用于外循环

时间:2012-11-11 17:20:16

标签: javascript jquery animation loops

我正在尝试对图像,它们的位置和尺寸执行一些jquery动画。我要做的是将图像单击移动到最大图像的位置(位置1,p1,图像)。

到目前为止,我能够将每张图像旋转到下一个前移位置。

您可以在此fiddle中看到。

我试图将函数movement置于循环中

for(var x = 0; x < 3; x++){
    movement(checker);
} 

起初我以为我希望将每个元素的3个位置向前移动,但事实并非如此。没有任何明显的事情发生。注意:checker是所点击图片的ID号。

我还认为让movement函数继续使用元素(16)的数量也会导致它在某种程度上解决问题。我将它改为32,期望每个元素移动2个位置。

function movement(checker){
    var count = 1;
    var first, last, positions, dimensions, leftPos, topPos, imgWidth, imgHeight;
    while(count<=32){//Increasing the loops to 32 from 16
        if(checker == 0){
            checker = 16;
        }

        first = d.e("p"+checker);


        if(checker == 1){
            last = d.e("p"+16);

    }else{
        last = d.e("p"+(checker-1));
    }
    //console.log(checker);
    positions = findPos(last);
    dimensions = getCanvas(last);
    leftPos = positions[0]; topPos = positions[1];
    imgWidth = dimensions[0]; imgHeight = dimensions[1];
    $("#p"+checker).animate({"left":leftPos, "top":topPos, "width":imgWidth, "height":imgHeight}, "fast");
    checker--; count++;

} 

我现在迷失了做什么。理想情况下,我想做的是把它放在一个循环中,参数“继续直到检查者离开,顶部位置==左边和顶部位置p1(初始)”。

所以我的问题是让元素在点击上移动多个位置。我不确定我是否采取了正确的方法,但任何帮助都将不胜感激。

提前谢谢你。

1 个答案:

答案 0 :(得分:1)

//move object
// current status: index of largest picture
var status = 1;

function movement(checker){
    var count = 1;
    var first, last, positions, dimensions, leftPos, topPos, imgWidth, imgHeight;
    while(count<=16){
        if(checker == 0){
            checker = 16;
        }
        first = d.e("p"+checker);

        if(checker == 1){
            last = d.e("p"+16);

        }else{
            last = d.e("p"+(checker-1));
        }    
        //console.log(checker);
        positions = findPos(last);
        dimensions = getCanvas(last);
        leftPos = positions[0]; topPos = positions[1];
        imgWidth = dimensions[0]; imgHeight = dimensions[1];
        var animateCount = 0;
        $("#p"+checker).animate({"left":leftPos, "top":topPos, "width":imgWidth, "height":imgHeight}, "fast", function() {
            animateCount++;
            // check if all 16 picture's animation was completed.
            if (16 == animateCount) {
                console.log('finished');
                // update the index of largest picture
                status = (status % 16) + 1;
                // rotate all again if status is not equal to checker
                if (status != checker)
                    movement(checker);
            }    
        });
        checker--; count++;

    }
}