Javascript图像随时间变化的位置

时间:2013-02-26 14:33:34

标签: javascript jquery html css3 animation

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

好的,在我身体末尾的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);
}

1 个答案:

答案 0 :(得分: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;
}
相关问题