1

基本上我想做的是让红色块在一段时间内从屏幕的左侧移动到右侧。我遇到的问题是页面运行到 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);
}
4

1 回答 1

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,我建议您不要重新发明轮子。使用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;
}
于 2013-02-26T14:36:51.123 回答