1

基本的に私がやろうとしているのは、赤いブロックを画面の左側から右側に移動させることです。私が直面している問題は、ページがアニメーションを表示せずに Java スクリプトを実行することです。ユーザーがJavaScriptの実行を完了するのを待っている間、ブロックは画面の反対側に移動されます。jQuery を使用してみましたが、それでも同じ結果が得られます。どんな助けでも大歓迎です。

私が持っている私の体の最後にある私のHTMLコードでOK:

    <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 に答える