[JS] iframeで読み込んだ要素の高さ指定(レスポンシブ対応)
<iframe>
で外部のHTMLを埋め込むとき、スクロールを発生させないためには <iframe>
にコンテンツ分の高さ指定が必要です(デフォルトは150px)。
しかしその外部HTMLがレスポンシブなコンテンツだと、高さを決め打ちしても結局ウィンドウ幅の変化に応じてスクロールが発生してしまいます。
当記事では、<iframe>
の高さ指定をJS(jQuery)でレスポンシブに対応させる方法を紹介します。
親と子が同一ドメインの場合
1つ目は、当ブログ(www.mgtnsn.com)と同一ドメインのHTMLを<iframe>
で読み込んで高さ調整するサンプルです。
URL: https://www.mgtnsn.com/demo/iframe-responsive-height/
同一ドメインの場合、jQueryのcontents()
を使って外部HTMLの情報にアクセスできます。
これを使って高さ調整が可能です。
<iframe src="https://www.mgtnsn.com/demo/iframe-responsive-height/" id="iframe-1"></iframe>
$(function(){
var $iframe = $('#iframe-1');
setTimeout(function(){
$iframe.height($iframe.contents().find('html').innerHeight());
},0);
$(window).on('resize', function(){
$iframe.height($iframe.contents().find('html').innerHeight());
});
});
表示結果
ウィンドウ幅を変更すると、コンテンツに合った高さに自動で調整されます。
親と子が違うドメインの場合
2つ目は、当ブログ(www.mgtnsn.com)とは違うドメインのHTMLを<iframe>
で読み込んで高さ調整するサンプルです。
URL: https://mgtnsn.github.io/mgtnsncom-blog/iframe-responsive-height/
別ドメインの場合、先ほどのcontents()
では情報にアクセスできません。
代わりに、window.postMessage()
というメソッドを活用します。
・子を編集できる(<script>を追加できる)ことが条件となります。
「子」に書くJS
window.addEventListener('load', postSize, false);
window.addEventListener('resize', postSize, false);
function postSize(e){
setTimeout(function(){
var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
if (typeof target != 'undefined' && document.documentElement.offsetHeight)
var j = {'execFlg':'autoHeight', 'height':document.documentElement.offsetHeight};
target.postMessage(j, '*');
},0);
}
「親」に書くHTML・JS
<iframe src="https://mgtnsn.github.io/mgtnsncom-blog/iframe-responsive-height/" id="iframe-2"></iframe>
window.addEventListener('message', receiveSize, false);
function receiveSize(e) {
setTimeout(function(){
if (e.origin === 'https://mgtnsn.github.io' && e.data.execFlg === 'autoHeight') {
$('#iframe-2').css('height',e.data.height + 'px');
}
},0);
}
※注:開始の $(function(){ ... })
は不要です。
表示結果
ウィンドウ幅を変更すると、コンテンツに合った高さに自動で調整されます。