2013-03-06 18 views
0

我想为图片添加动画,以便当用户输入X和Y偏移值时,图片将从窗口的左上角开始,然后从左向右移动,最后移动图片一次只能上到最后一个像素的位置。卡在动画中的Javascript

这里是我的代码,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

'setTimeout'没有一个大写'o'。 – Ryan 2013-03-06 23:52:17

+0

你为什么不声明你的变量? 'var'不是可选的。你只需创建一堆全局变量。 – elclanrs 2013-03-06 23:52:45

+0

另外,你并没有在任何地方设置图像的位置。你需要在某个时候使用类似style.top和style.left的东西。 – 2013-03-06 23:55:44

回答

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); 
    } 
} 
+0

我现在明白了,非常感谢! – 2013-03-07 01:07:31

+0

我可以问一下'1 *'是什么?看来该功能可以在没有它的情况下运行它。 – 2013-03-07 01:16:36

+1

我假设他确保表单中的值是整数而不是字符串。它的作用与parseInt相同(document.getElementById('yva').value,10); – 2013-03-07 01:23:32