質問

iframe width および height 自動調整して、ほとんど適合しないソリューションが必要コンテンツ。ポイントは、 iframe が読み込まれた後に幅と高さを変更できることです。 iframeに含まれるボディの寸法の変化に対処するには、イベントアクションが必要だと思います。

役に立ちましたか?

解決

<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

window.addEventListener('DOMContentLoaded', function(e) {

    var iFrame = document.getElementById( 'iFrame1' );
    resizeIFrameToFitContent( iFrame );

    // or, to resize all iframes:
    var iframes = document.querySelectorAll("iframe");
    for( var i = 0; i < iframes.length; i++) {
        resizeIFrameToFitContent( iframes[i] );
    }
} );

</script>

<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>

他のヒント

Cross-browser jQueryプラグイン

クロスボウザー、クロスドメイン ライブラリ > mutationObserver はコンテンツに合わせてiFrameのサイズを維持し、 postMessage はiFrameとホストページ間で通信します。 jQueryの有無にかかわらず動作します。

これまでに説明したすべてのソリューションは、一度限りのサイズ変更のみを考慮しています。内容が変更された後にiFrameのサイズを変更できるようにしたいと言っています。これを行うには、iFrame内で関数を実行する必要があります(コンテンツが変更されたら、イベントが発生してコンテンツが変更されたことを通知する必要があります)。

iFrame内のコードはiFrame内のDOMに限定されているように見え(iFrameを編集できませんでした)、iFrameの外部で実行されるコードはiFrameの外部のDOMでスタックしていました( iFrame内からのイベントをピックアップできませんでした)。

解決策は、jQueryにどのDOMを使用するかを通知できることを(同僚の支援により)発見したことから生まれました。この場合、親ウィンドウのDOM。

そのため、このようなコードは必要なことを行います(iFrame内で実行する場合):

<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("#IDofControlFiringResizeEvent").click(function () {
            var frame = $('#IDofiframeInMainWindow', window.parent.document);
            var height = jQuery("#IDofContainerInsideiFrame").height();
            frame.height(height + 15);
        });
    });
</script>

iframeコンテンツが同じドメインからのものである場合、これはうまく機能します。ただし、jQueryが必要です。

$('#iframe_id').load(function () {
    $(this).height($(this).contents().height());
    $(this).width($(this).contents().width());
});

動的にサイズを変更するには、次のようにします:

<script language="javaScript">
<!--
function autoResize(){
    $('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>

次に、iframeがロードするページでこれを追加します:

<script language="javaScript">
function resize()
{
    window.parent.autoResize();
}

$(window).on('resize', resize);
</script>

埋め込み用のワンライナーソリューション: 最小サイズから始まり、コンテンツサイズまで増加します。スクリプトタグは不要です。

<iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>

jQueryを使用したくない場合のクロスブラウザソリューションは次のとおりです。

/**
 * Resizes the given iFrame width so it fits its content
 * @param e The iframe to resize
 */
function resizeIframeWidth(e){
    // Set width of iframe according to its content
    if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
        e.width = e.contentWindow.document.body.scrollWidth;
    else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
        e.width = e.contentDocument.body.scrollWidth + 35;
    else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
        e.width = e.contentDocument.body.offsetWidth + 35;
}

このコードを使用して、ページにロードするときにすべてのiframeの高さを自動的に調整します(css auto Heightを使用)。テスト済みで、IE、FF、Chrome、Safari、Operaで動作します。

function doIframe() {
    var $iframes = $("iframe.autoHeight"); 
    $iframes.each(function() {
        var iframe = this;
        $(iframe).load(function() {
            setHeight(iframe);
        });
    });
}

function setHeight(e) {
  e.height = e.contentWindow.document.body.scrollHeight + 35;
}

$(window).load(function() {
    doIframe();
});

地球上のすべてを試した後、これは本当にうまくいきます。

index.html

<style type="text/css">
html, body{
  width:100%;
  height:100%;
  overflow:hidden;
  margin:0px;   
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>

これは堅牢なソリューションです

function resizer(id)
{

var doc=document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;

var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );

document.getElementById(id).style.height=height;
document.getElementById(id).style.width=width;

}

html

<IFRAME SRC="blah.php" id="iframe1"  onLoad="resizer('iframe1');"></iframe>

上記のGarnaphの優れたソリューションを少し変更しました。イベントの直前のサイズに基づいて、彼のソリューションがiframeサイズを変更したように見えました。私の状況(iframe経由の電子メール送信)では、送信直後にiframeの高さを変更する必要がありました。たとえば、検証エラーや「ありがとう」を表示します。送信後のメッセージ。

ネストされたclick()関数を削除し、iframe htmlに追加しました:

<script type="text/javascript">
    jQuery(document).ready(function () {
        var frame = $('#IDofiframeInMainWindow', window.parent.document);
        var height = jQuery("#IDofContainerInsideiFrame").height();
        frame.height(height + 15);
    });
</script>

私のために働いたが、クロスブラウザ機能についてはわからなかった。

いくつかの方法があります:

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</body>

その他の代替

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>

上記のように2つの代替手段でスクロールを非表示にする

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
</body>

2番目のコードでハッキング

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
</body>

iFrameのスクロールバーを非表示にするには、親を&quot; overflow:hidden&quot;にします。スクロールバーを非表示にし、iFrameを最大150%の幅と高さにします。これにより、スクロールバーがページの外側に強制的に配置されます。 。これにより、iFrameのスクロールバーが全幅で非表示になります!

source:set iframe自動高さ

上記の方法ではすべてが機能しません。

javascript:

function resizer(id) {
        var doc = document.getElementById(id).contentWindow.document;
        var body_ = doc.body, html_ = doc.documentElement;

        var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
        var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);

        document.getElementById(id).style.height = height;
        document.getElementById(id).style.width = width;

    }

html:

<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv"  >
         <input id="txtHeight"/>height     <input id="txtWidth"/>width     
        <iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0"  ></iframe>
        <iframe src="left.aspx" name="leftFrame" scrolling="yes"   id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
        <iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; "  onload="resizer('Iframe2');" ></iframe>
</div>

環境:IE 10、Windows 7 x64

IFRAMEコンテンツと親ウィンドウの両方を制御できる場合、 iFrame Resizer が必要です。 。

このライブラリを使用すると、同じiFrameとクロスドメインiFrameの両方の高さと幅を自動的にサイズ変更して、含まれるコンテンツに合わせることができます。 iFrameの使用に関する最も一般的な問題に対処するためのさまざまな機能を提供します。以下が含まれます。

  • コンテンツのサイズに合わせてiFrameの高さと幅を変更します。
  • 複数のネストされたiFrameで動作します。
  • クロスドメインiFrameのドメイン認証。
  • さまざまなページサイズの計算方法を提供して、複雑なCSSレイアウトをサポートします。
  • MutationObserverを使用してページのサイズを変更する可能性のあるDOMへの変更を検出します。
  • ページのサイズ変更を引き起こす可能性のあるイベント(ウィンドウのサイズ変更、CSSアニメーションと遷移、向きの変更、およびマウスイベント)を検出します。
  • postMessageを介したiFrameとホストページ間の簡略化されたメッセージング
  • iFrameのページリンクを修正し、iFrameと親ページ間のリンクをサポートします。
  • カスタムのサイズ変更およびスクロール方法を提供します。
  • 親の位置とビューポートのサイズをiFrameに公開します。
  • ViewerJSと連携してPDFおよびODFドキュメントをサポートします。
  • IE8までのフォールバックサポート。

誰かがここに来た場合: iframeからdivを削除したときにソリューションに問題がありました-iframeは短くなりませんでした。

ジョブを実行するJqueryプラグインがあります:

http:// www。 jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html

いくつかの実験の後、別の解決策を見つけました。私はもともと、この質問に対して「ベストアンサー」としてマークされたコードを試しましたが、うまくいきませんでした。私の推測は、当時の私のプログラムのiframeが動的に生成されたためです。ここに私が使用したコードがあります(それは私のために働きました):

ロードされるiframe内のJavascript:

window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };
  

スクロールバーを削除するには、高さに4ピクセル以上を追加する必要があります(iframeの奇妙なバグ/効果)。幅はさらに奇妙で、体の幅に18pxを追加しても安全です。また、iframe本体のCSSが適用されていることを確認してください(下)。

html, body {
   margin:0;
   padding:0;
   display:table;
}

iframe {
   border:0;
   padding:0;
   margin:0;
}

iframeのhtmlは次のとおりです。

<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>

iframe内のすべてのコードは次のとおりです。

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>File Upload</title>
    <style type="text/css">
    html, body {
        margin:0;
        padding:0;
        display:table;
    }
    </style>
    <script type="text/javascript">
    window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };
    </script>
</head>
<body>
    This is a test.<br>
    testing
</body>
</html>

Chromeでテストを行い、Firefox(Windows XPで)で少しテストを行いました。まだテストが必要なので、これがどのように機能するか教えてください。

このリサイザーがよりよく機能することがわかりました:

function resizer(id)
{

    var doc = document.getElementById(id).contentWindow.document;
    var body_ = doc.body;
    var html_ = doc.documentElement;

    var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight,     html_.scrollHeight, html_.offsetHeight );
    var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );

    document.getElementById(id).height = height;
    document.getElementById(id).width = width;

}

スタイルオブジェクトが削除されていることに注意してください。

jQueryでは、これが私にとって最良のオプションであり、本当に役立ちます!!それがあなたを助けるのを待っています!

iframe

<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>

jQuery

<script>            
        var valueSize = $( "#iframe" ).offset();
        var totalsize = (valueSize.top * 2) + valueSize.left;

        $( "#iframe" ).height(totalsize);            

</script>

「ゴーストのような」ものを作成することができます。存在しないように動作するIFrame。

http://codecopy.wordpressをご覧ください。 com / 2013/02/22 / ghost-iframe-crossdomain-iframe-resize /

基本的には、イベントシステム parent.postMessage(..)を使用します。 https://developer.mozilla.org/en-US/docs/DOM /window.postMessage

これは、すべての最新ブラウザーで動作します!

これは私がやる方法です(FF / Chromeでテスト済み):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>

投稿が古いことは知っていますが、これは別の方法だと思います。コードに実装しました。ページの読み込みとページのサイズ変更の両方で完全に動作します:

var videoHeight;
var videoWidth;
var iframeHeight;
var iframeWidth;

function resizeIframe(){
    videoHeight = $('.video-container').height();//iframe parent div's height
    videoWidth = $('.video-container').width();//iframe parent div's width

    iframeHeight = $('.youtubeFrames').height(videoHeight);//iframe's height
    iframeWidth = $('.youtubeFrames').width(videoWidth);//iframe's width
}
resizeIframe();


$(window).on('resize', function(){
    resizeIframe();
});

ヘッダーに配置するJavascript:

function resizeIframe(obj) {
        obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
      }

iframe htmlコードは次のとおりです:

<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>

Cssスタイルシート

&gt;

.spec_iframe {
        width: 100%;
        overflow: hidden;
    }

angularjsディレクティブ属性の場合:

G.directive ( 'previewIframe', function () {
return {
    restrict : 'A',
    replace : true,
    scope : true,
    link : function ( scope, elem, attrs ) {
        elem.on ( 'load', function ( e ) {
            var currentH = this.contentWindow.document.body.scrollHeight;
            this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + 'px';
        } );
    }
};
} );

パーセンテージに注意して、iframe、テキスト、広告などで通常行われるスケーリングに対抗できるように挿入し、スケーリングが実装されていない場合は単に0を入力します

コンテンツが非常に単純なhtmlである場合、最も簡単な方法はjavascriptでiframeを削除することです

html:

<div class="iframe">
    <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
</div>

javascript:

function removeIframe(obj)(
    var iframeDocument = obj.contentDocument || obj.contentWindow.document;
    var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
    obj.remove();
    document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
}

これは、オンロード時または状況が変化したときの方法です。

parent.jQuery("#frame").height(document.body.scrollHeight+50);

コンテキスト

私はこれをWeb拡張のコンテキストで自分でやらなければなりませんでした。このWeb拡張機能は、各ページにUIを挿入し、このUIは iframe 内にあります。 iframe 内のコンテンツは動的であるため、 iframe 自体の幅と高さを再調整する必要がありました。

React を使用していますが、この概念はすべてのライブラリに適用されます。

私の解決策(これは、ページとiframeの両方を制御することを前提としています)

iframe 内で、 body スタイルを非常に大きなサイズに変更しました。これにより、内部の要素が必要なスペースをすべて使用してレイアウトできるようになります。 width height を100%にするのはうまくいきませんでした(iframeにはデフォルトの width = 300px heightがあるので、 = 150px

/* something like this */
body {
  width: 99999px;
  height: 99999px;
}

次に、すべてのiframe UIをdiv内に挿入し、いくつかのスタイルを指定しました

#ui-root {
  display: 'inline-block';     
}

この#ui-root 内でアプリをレンダリングした後( React componentDidMount 内でこれを行います)このdivの寸法を計算します window.postMessage

を使用して親ページに同期します。
let elRect = el.getBoundingClientRect()
window.parent.postMessage({
  type: 'resize-iframe',
  payload: {
    width: elRect.width,
    height: elRect.height
  }
}, '*')

親フレームで次のようにします:

window.addEventListener('message', (ev) => {
  if(ev.data.type && ev.data.type === 'resize-iframe') {
    iframe.style.width = ev.data.payload.width + 'px'
    iframe.style.height = ev.data.payload.height + 'px'
  }
}, false)

明らかに多くのシナリオがありますが、ドキュメントとiframeに同じドメインがあり、これをiframeコンテンツの最後に追加することができました:

var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';

これは親コンテナを「検出」し、50ピクセルのファッジファクターに追加する長さを設定してスクロールバーを削除します。

ドキュメントの高さの変化を「観察」するものは何もありません。これは私のユースケースには必要ありませんでした。私の答えでは、親/ iframeコンテンツに焼き付けられたIDを使用せずに、親コンテナを参照する手段をもたらします。

シンプルさ:

var iframe = $("#myframe");
$(iframe.get(0).contentWindow).on("resize", function(){
    iframe.width(iframe.get(0).contentWindow.document.body.scrollWidth);
    iframe.height(iframe.get(0).contentWindow.document.body.scrollHeight);
});

これはインラインCSSのみを使用します:

<iframe src="http://example.com" style="resize: both;"               
        onload="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';"
        onresize="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';">
</iframe>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top