17

一般的に、私は iframe の使用に反対していますが、それは私の特定の問題を解決しました。

問題は、Web ページに tinyMCE エディターがあることです。ユーザーがこのエディターを使用してコンテンツを作成すると、コンテンツは HTML として Web アプリケーションに送信されます。このコンテンツは div に表示されます。tinyMCE は、絶対的な位置を持つスタイルを追加することが多く、Web アプリケーションの残りの部分を壊すものを追加します。

テストしたところ、新しい HTML 5が私の状況iframe srcdoc="<p>Some HTML</p>"seamless="true"ぴったりであることがわかりました。それはシームレスに見え、コンテンツのスタイルと私のスタイルはそのままでした. 悲しいことに、HTML5 srcdoc 属性はまだ Android でサポートされていないことがわかりました ( http://w3schools.com/html5/tryit.asp?filename=tryhtml5_iframe_srcdocは、chrome と android ブラウザーで異なる結果をもたらします)。

質問は次のとおりです。受信したコンテンツのすべてのスタイルを保持し、それを div に含める iframe srcdoc に代わるものはありますか?

4

3 に答える 3

22

次のように iframe のドキュメントに書き込むことができます。

const html = '<body>foo</body>';
const iframeDocument = document.querySelector('iframe#foo').contentDocument;
const content = `<html>${html} </html>`;
iframeDocument.open('text/html', 'replace');
iframeDocument.write(content);
iframeDocument.close();
于 2013-07-17T18:21:46.983 に答える
9

コメントによる eicto で示唆されているように、jquery を使用して、ready-event で iframe を埋めることができます。iframe の高さをコンテンツの高さに調整するために、いくつかの汚いハックを適用する必要がありましたが、最終的に使用したコードは多かれ少なかれ次のとおりです。

HTML

<!-- IMPORTANT! Do not add src or srcdoc -->
<!-- NOTICE!    Add border:none to get a more "seamless" integration -->
<iframe style="border:none" scrolling="no" id="myIframe">
    Iframes not supported on your device
</iframe>

JS

// Wait until iFrame is ready (body is then available)
$('#myIframe').ready(function() {

    var externalHtml = '<p>Hello World!</p>';

    // Find the body of the iframe and set its HTML
    // Add a wrapping div for height hack
    // Set min-width on wrapping div in order to get real height afterwords
    $('#myIframe').contents().find('body')
        .html('<div id="iframeContent" style="min-width:'+$('body').width()+'px">'
            +externalHtml
            +'</div>'
    );

    // Let the CSS load before getting height 
    setTimeout(function() {
        // Set the height of the iframe to the height of the content
         $('#myIframe').css('height', 
             $('#myIframe').contents()
             .find('#iframeContent').height() + 'px' 
         );
    },50);
});
于 2012-11-04T12:01:55.583 に答える