purazumakoiの[はてなブログ]

技術メモから最近はライフログも増えてきてます。

クロスブラウザでiframeの高さを内容コンテンツの高さに合わせる

コンテンツ内の他のページをiframeで読み込んで表示したときスクロールを無しにしたい。

ヘッダとかフッダとか消して、コンテンツ部分だけをiframeに挿入する為。
ただ高さを取得することは割と簡単だったが、
ブラウザの戻るボタンで戻った時もコンテンツの高さを正しくとろうと思って手こずりました。

コード
// jquery読み込み。1.4.4じゃなくても1.3とかでも大丈夫でしょう。
<script language="javascript" type="text/javascript" src="../../js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// <![CDATA[
$(function(){
 //htmlファイル を読み込む
 // 読み込みは同一ドメイン内で
 var ifm = $('#dIframe').append('<iframe src="../../hogehoge/index.html" frameborder="0">').find('> :last-child');
 
 //読み込み完了したら内容を変更する
 ifm.load(function(){
 
  // iframeのサイズ指定
  if (typeof $(this).attr('height') == 'undefined' || $(this).attr('height') == '' ) {
   // IE
   if(jQuery.browser.msie ){
    // -100はiframe内のコンテンツでdisplay:noneをしているheader、footerの分
    $(this).height( (this.contentWindow.document.body.scrollHeight) -100 );
   }
   // others
   else {
    $(this).height( (this.contentWindow.document.documentElement.offsetHeight) -100 );
   }
  }

  // iframe内のheadにcssを追加
  var idoc = $(this).contents();
  var ihead = idoc.find('head');
  var cs = idoc[0].createElement('link')

  // このcss内でmain部分以外のdisplayをnone
  cs.href = '/css/iframe.css';
  cs.type = 'text/css';
  cs.rel = 'stylesheet';
  ihead[0].appendChild(cs);

 });
 
});
// ]]>
</script>

・
・
・

// body内のこのdiv内にiframeが読み込まれる
<div id="dIframe"></div>
動作確認ブラウザ

IE6(純正)
IE7,8(IE Tester)
IE9 Beta
Fx2, 3.5
Op10.63
chrome9
safari5

その他メモ

IE以外はthis.contentWindow.document.documentElement.offsetHeightでとれた
IE(全て)はthis.contentWindow.document.body.scrollHeightでとれた
IE6,7はthis.contentWindow.document.documentElement.scrollHeightでとれた