1

アニメーションを処理するために、javascript で複数の惑星オブジェクトを作成しています。

アニメーションは各惑星で正常に動作しますが、IE 6/7 で「15 文字 2 行目にオブジェクトが必要です」というエラーが表示されます。

コード:

var earthObj = null;
var mercObj = null;
var jupiObj = null;
var animate;
function init()
{
    mercObj = document.getElementById('mercury');
    earthObj = document.getElementById('earth');
    jupiObj = document.getElementById('jupiter');

    mercObj.style.position= 'relative';  
    mercObj.style.left = '54px'; 
    mercObj.style.visibility = 'hidden';

    earthObj.style.position= 'relative';  //error on this line
    earthObj.style.left = '80px'; 
    earthObj.style.top = 300px';
}
4

3 に答える 3

1

オブジェクトを呼び出そうとする前に、それが存在するかどうかをテストしてください。

earthObj = document.getElementById('earth');
if(!earthObj) {
  alert("Could not find Earth");
  return;
}
于 2012-05-14T00:08:52.043 に答える
0

私はMacを使用していますが、試すIEがありません。次のようにコードを変更すると、同じエラーが発生しますか?

function init() {
  var earthObj = null;
  var mercObj = null;
  var jupiObj = null;
  var animate;

  mercObj = document.getElementById('mercury');
  earthObj = document.getElementById('earth');
  jupiObj = document.getElementById('jupiter');

  mercObj.style.position= 'relative';  
  mercObj.style.left = '54px'; 
  mercObj.style.visibility = 'hidden';


  !earhtObj && alert("There is no element with id 'earth'");
  earthObj.style.left = '80px'; 
  earthObj.style.top = '300px';
  earthObj.style.position= 'relative'; 
}

この投稿にたどり着き、グローバル変数がdomオブジェクトと同じ名前を取得したときにトリガーされるIE6/7バグにエラーが関連している可能性があると考えました。

また、をブロックの最後に移動しearthObj.style.position= 'relative';、エラーがリーパーになることを期待していますearthObj.style.left = '80px';

于 2012-05-14T00:06:00.407 に答える
0

IEでは、スクリプトが定義/生成されたHTML要素の後にある場合、関数が機能することがわかりました。

つまり、スクリプトを HTML ドキュメントの先頭ではなく末尾に配置するか、jquery の ready 関数を使用します。

$(function() {
   mercObj = document.getElementById('mercury');
});
于 2014-11-06T16:24:03.387 に答える