例えば、以下のように。
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
スクロールを使わずに、中のコンテンツに合わせて高さを調整できるようにしたい。
これを <head>
セクションに追加します。
<script>
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
そして、iframeをこのように変更します。
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
sitepoint discussion]1で見つけたものです。
hjpotter92*さんの提案は、Safariでは機能しません。 スクリプトに若干の修正を加え、Safariでも動作するようにしました。
唯一の変更点は、いくつかのブラウザで高さを下げられるようにするため、読み込みのたびに高さを0にリセットすることです。
これを <head>
タグに追加します。
<script type="text/javascript">
function resizeIframe(obj){
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
そして、以下のように、iframeに onload
属性を追加します。
<iframe onload='resizeIframe(this)'></iframe>
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
}
document.getElementById(id).height=(newheight) + "px";
document.getElementById(id).width=(newwidth) + "px";
}
これをあなたのiframeに追加します。 onload="autoResize('youriframeid')"