1

正しく動作しない非常に単純な JavaScript/jquery コードがあります。問題は、ID 'circle' を持つ div の配置が、ループの実行時に計算されないように見えることです。問題が発生している理由と、利用可能な修正があるかどうかを知る必要があるだけです。

ここにリンクhttp://jsfiddle.net/TDRyS/ があります。

コード:

var maxa = document.width;
var maxb = document.height;
$(document).ready(function() {

    dothis();
});

function dothis() {
    var left = parseInt(document.getElementById('circle').style.left);
    var top = parseInt(document.getElementById('circle').style.top);
    if (top >= 500) {
        $("#circle").animate({
            top: "-=" + Math.floor(Math.random() * 100 + 1) + "px",
            left: "-=" + Math.floor(Math.random() * 100 + 1) + "px"
        }, 1000);
    }
    else {
        $("#circle").animate({
            top: "+=" + Math.floor(Math.random() * 100 + 1) + "px",
            left: "+=" + Math.floor(Math.random() * 100 + 1) + "px"
        }, 1000);

    }

    dothis();
}​
4

3 に答える 3

3

関数を再度呼び出す前に、setTimeout を設定する必要があります\ 関数をコールバックとして渡します

ライブデモ

完全なコード:

var maxa = document.width;
var maxb = document.height;
var up = false;
$(document).ready(function() {

    doThis();
});

function doThis() {

    var left = parseInt(document.getElementById('circle').style.left);
    var top = parseInt(document.getElementById('circle').style.top);
    if (top < 50) {
        up = false;
    }
    if (top >= 500 || up) {

        up = true;
        $("#circle").animate({
            top: "-=" + Math.floor(Math.random() * 100 + 1) + "px",
            left: "-=" + Math.floor(Math.random() * 100 + 1) + "px"
        }, 500, doThis);
    }
    else {
        $("#circle").animate({
            top: "+=" + Math.floor(Math.random() * 100 + 1) + "px",
            left: "+=" + Math.floor(Math.random() * 100 + 1) + "px"
        }, 500, doThis);

    }
}​
于 2012-06-24T16:09:39.133 に答える
1

これにはいくつかの問題があります。

  1. DOM 要素の「style」プロパティから CSS からのスタイル情報を読み取ることはできません。とにかくjQueryを使用しています。スタイル情報を提供できます。
  2. 「animate」の呼び出しは同期的に完了しません。「dothis」を 3 番目のパラメーターとして渡すと、アニメーションが完了すると jQuery が関数を呼び出します。

ここに作業バージョンがあります。

于 2012-06-24T16:15:09.433 に答える
0

左と上を計算するには、次も使用できます。

$("#circle").position().left // or .top (relative to parent object)

$("#circle").offset().left // or .top (relative to window)

とにかく、「アニメーション」を継続的に呼び出しているため、コードが間違っているようです。別のアニメーションを呼び出す前に、アニメーションを「実行」する時間はありません (また、top>500px の場合は厄介な関数の再帰を行います)。

あなたがしなければならないことは、時間遅延を使用するか、何らかのイベントを使用して、アニメーションが完了するのを待つことです.top>500の場合、タイマーを使用してnミリ秒ごとにチェックします. その場合、現在のアニメーションを停止し、反対方向に新しいアニメーションを開始します

于 2012-06-24T16:10:02.523 に答える