適当な思いつきで書くブログ

UbuntuやPerlやJavaScriptやVimやZshやShellScriptやMySQLと戯れている中で適当な思いつきでやってみたことを書いています。

jQuery.jsでiframeの高さを中身のコンテンツに合わせる

iframeの中身を扱うには.contents()を使用する。

$(document).ready(function(){
  $('iframe').load(function() {
    $(this).css('height', $(this).contents().height() + 'px');
  }); 
});

そんだけ。
と思ったらこれだとIEで取得できない(IE8で確認)。
.find('body')でbodyの高さをとってあげる必要がある。

$(document).ready(function(){
  $('iframe').load(function() {
    $(this).css('height', $(this).contents().find('body').height() + 'px');
  }); 
});

ボディ、ボディを狙え。