問題の HTML 要素のサイズを取得しようとして、問題に直面することがあります。
JavaScript コードをトレースしていると、この要素の幅と高さが 0 として返されることがわかります。
ブラウザのコンソールで同じコードを実行すると、正しいサイズが返されます。
この問題を示すコード例は次のとおりです。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>Decorate image with button</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
jQuery(function($){
// Decorate image, wrapped to link to movie with "Play" button
$("a > img").each(function(){
var img = $(this);
var a = img.parent();
var w = img.width();
var h = img.height();
a.html(" \
<table style='position: absolute;'> \
<tr style='background-color:transparent;'> \
<td style='width: 100%; background-color: transparent;'> \
<img src='http://30ttclan.extra.hu/e107_images/RTEmagicC_play_button.png.png' style='display: block; width: 25%; margin-left:auto; margin-right: auto;'></img> \
</td> \
</tr> \
</table>");
a.append(img);
// Make height of table equals to height of image
a.find("> table").width( w );
a.find("> table").height( h );
});
});
</script>
</head>
<body>
<a href="http://movies.apple.com/media/us/mac/ilife/iphoto/2010/features/apple-ilife-iphoto-features_whats_new-us-20100727_r848-9cie.mov">
<img src="http://kelsocartography.com/blog/wp-content/uploads/2009/01/iphoto09_map.png">
</a>
</body>
</html>
このコードは、アンカーにラップされた画像を取得し、その上に中央に配置する必要がある「再生」ボタンで装飾します。
テーブルセルはセンタリングに使用されます。
Firefox では問題なく動作しますが、Safari 5 では動作しません。
コードをトレースすると、幅と高さを取得する "w" 変数と "h" 変数の値が 0 であることがわかります。
ブラウザのコンソールから言うと
$("a > img").width()
正しいサイズの画像が得られます。
私は何かが欠けていると思います...
「レンダリング完了」のようなイベントをキャッチする必要があると思います...しかし、私の知る限り、それらはDOMに表示されません。
HTML 要素がレンダリングされ、100% 確実に表示されたときに、正しいサイズを扱っていることをどのように知ることができますか?