2012-11-03 42 views
12

一般來說,我反對使用iframe,但它解決了我的一個特殊問題。替代iframe srcdoc?

事情是,我在網頁上有一個tinyMCE編輯器。在用戶使用該編輯器製作內容後,內容將作爲HTML發送到Web應用程序。這個內容然後顯示在一個div中。事情是tinyMCE經常添加樣式,絕對位置爲,以及與網絡應用程序的其餘部分相關的東西。

當測試時,我發現新的HTML 5 iframe srcdoc="<p>Some HTML</p>"seamless="true"是完美的我的情況。它看起來無縫,內容風格和我的風格完好無損。可悲的是我現在看到Android5還沒有支持HTML5 srcdoc屬性(http://w3schools.com/html5/tryit.asp?filename=tryhtml5_iframe_srcdoc在chrome和android瀏覽器中產生不同的結果)。

所以問題是:是否有任何替代的iframe srcdoc將保留接收到的內容的所有風格,並將其包含在一個div?

+0

更改編輯器?網上有很多編輯器 –

+1

也可能你喜歡這個例子,它演示瞭如何在同一個源代碼上使用iframe。 http://jsfiddle.net/oceog/r4VPr/ –

+0

謝謝,這做了一些修改的伎倆! – Sindre

回答

10

正如eicto評論所建議的那樣,可以使用jquery在ready事件中填充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); 
}); 
+1

只要沒有任何內容是不可信任和不可靠的,就不要這樣做 - 如果用戶正在粘貼代碼片段,這可能是可能的... –

13

你可以寫一個iframe的像這樣的文檔:

var iframeDocument = document.querySelector('#foo').contentWindow.document; 
var content = '<html></html>'; 
iframeDocument.open('text/html', 'replace'); 
iframeDocument.write(content); 
iframeDocument.close(); 
1

使用新的Data URI Scheme。 示例:

var content = "<html></html>";
document.getElementById("my_iframe_id").src = "data:text/html;charset=UTF-8," + content;
+0

請參閱http://msdn.microsoft.com/zh-cn/library/ cc848897(v = VS.85).aspx 數據URI僅支持以下元素和/或屬性。 object(僅限圖片) img input type = image 鏈接 接受URL的CSS聲明,如background,backgroundImage等。 – jbiddick