在Javascript中停留在动画中

时间:2013-03-06 23:51:15

标签: javascript

我想为图片设置动画,以便当用户输入X和Y偏移值时,图片将从窗口的左上角开始,然后从左向右移动,最后将图片自上而下移动到最终位置一次一个像素。

这是我的代码http://jsfiddle.net/nMdNk/3/

在我的javascript中,我有:

function moveRight() {
    hx = document.getElementById("xval").value;
    imgx = document.getElementById("picture").clientX; //get current X from image
    for (a = 0; a <= imgx; a++;) {

        if (imgx == hx) {
            moveDown();
        } else {
            setTimeOut(moveRight, 1000);
        }
    }
}

function moveDown() {
    hy = document.getElementById("yval").value;
    imgy = document.getElementById("picture").clientY; //get current Y from image
    for (b = 0; b <= imgy; b++;) {

        if (imgy = hy) {
            return; //stop when reach to final destination 
        } else {
            setTimeOut(moveDown, 1000);
        }
    }
}

我想我正在为图片的x和y坐标检索错误的元素,但不太确定。任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

我已经为您修改了代码并将其放入此JSFiddle。我做了一些改变,但不是太激烈。主要的一个是你的for循环是不必要的,并且会导致奇怪的行为 - 通过在setTimeout中调用你的函数,for循环基本上是被绕过的。因此,对于for循环中的每次迭代,您将通过setTimeout引发一个全新的操作链。例如,如果您没有检查(imgx == hx),您的脚本将无限期地继续,即使使用for循环也是如此。

function init(){
    document.getElementById("picture").style.left = '0px';
    document.getElementById("picture").style.top = '0px';
    moveRight();
}
function moveRight() {
    hx = 1 * document.getElementById("xval").value;
    imgx = document.getElementById("picture").offsetLeft; //get current X from image
    document.getElementById("picture").style.left = (imgx + 1) + 'px';
    if (imgx == hx) {
        moveDown();
    } else {
        setTimeout(moveRight, 10);
    }
}

function moveDown() {
    hy = 1 * document.getElementById("yval").value;
    imgy = document.getElementById("picture").offsetTop; //get current Y from image
    document.getElementById("picture").style.top = (imgy + 1) + 'px';
    if (imgy == hy) {
        return; //stop when reach to final destination 
    } else {
        setTimeout(moveDown, 10);
    }
}