2013-02-26 70 views
1

基本上我想要做的是让红色块在一段时间内从屏幕左侧移动到右侧。我遇到的问题是页面运行到java脚本而不显示动画。该块刚刚移动到屏幕的另一侧,而用户等待JavaScript完成运行。我已经尝试使用jQueries准备好,但我仍然得到相同的结果。任何帮助,将不胜感激。Javascript Image随着时间改变位置

在我身上结束我的HTML代码好吧,我有:

<script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script type="text/javascript" src="js/nexusStyle.js"></script> 
    <script>     
     $(document).append(function foo(){ 
      start(); 
     }); 
    </script> 

在我nexusStyle.js文件我有:

function start(){ 
    createBlock(); 
    var mHeight = getMonitorHeight(); 
    var mWidth = getMonitorWidth(); 
} 
function getMonitorWidth() { 
    return screen.width; 
} 
function getMonitorHeight(){ 
    return screen.height; 
} 
function horizontalMotion(maxWidth, img){ 
    for(var i=0; parseInt(i)<maxWidth; i+=50){ 
     img.style.left = i+"px"; 
     sleep(100); 
    } 
} 
function sleep(delay){ 
    var start = new Date().getTime(); 
    while(new Date().getTime()<start+delay); 
} 
function createBlock(){ 
    var img, left, top, interval; 
    interval = 100; 
    img = document.createElement('img'); 
    img.src = "img/blocks/redBlock.png"; 
    left = 0; 
    top = 200; 
    img.style.position = "absolute"; 
    img.style.left = left+"px"; 
    img.style.top = top+"px"; 
    document.body.appendChild(img); 
    horizontalMotion(getMonitorWidth(), img); 
} 
+0

如果您使用jQuery,为什么不使用'animate'函数? http://api.jquery.com/animate/ – js1568 2013-02-26 15:17:09

回答

1

作为开始有一些明显的事情错误:

移动全部在for循环中,它将同步执行直到完成。你需要将其推出当前进程的给浏览器的渲染时间:

function horizontalMotion(maxWidth, img){ 
    for(var i=0; parseInt(i)<maxWidth; i+=50){ 
     setTimeout(function(){ 
      img.style.left = i+"px"; 
      sleep(100); 
     },0); 
    } 
} 

也是你的文件准备应该是:

<script>     
    $(function(){ 
     start(); 
    }); 
</script> 

这只会停止正在运行的任何程序在你使用它的当前上下文中,这将是渲染线程。

function sleep(delay){ 
    var start = new Date().getTime(); 
    while(new Date().getTime()<start+delay); 
} 

而且即使使用setTimeout你将不得不与运动发生的事情一下子闹逃逸渲染过程。

编辑:

既然你已经使用jQuery我建议你不要推倒重来。 Use animate

$(function(){ 
    start(); 
}); 

var mHeight = getMonitorHeight(); 
var mWidth = getMonitorWidth(); 
var interval = 1000; 

function start(){ 
    var theIMG = createBlock(); 
    var iterations = getMonitorWidth() - 200; //the 200 should be replaced with your image width 
    $(theIMG).animate({left:iterations},interval); 
} 
function getMonitorWidth() { 
    return $(document).width(); 
} 
function getMonitorHeight(){ 
    return $(document).height(); 
} 
function createBlock(){ 
    var img, left, top; 
    img = document.createElement('img'); 
    img.src = "img/blocks/redBlock.png"; 
    left = 0; 
    top = 200; 
    img.style.position = "absolute"; 
    img.style.left = left+"px"; 
    img.style.top = top+"px"; 
    document.body.appendChild(img); 
    return img; 
} 
+0

谢谢你,也是js1568。我仍然不熟悉jQuery和JavaScript,因此我只是随时查找。 – jbeverid 2013-02-26 15:53:58

+0

我也去过那里。这需要一点时间,但至少你在尝试。祝你好运。 – 2013-02-26 15:54:27

相关问题