Alternatives to iframe srcdoc?
通常我反对使用iframe,但是它解决了我的一个特殊问题。
问题是我在网页上有一个tinyMCE编辑器。用户使用此编辑器制作内容后,该内容将作为HTML发送到Web应用程序。然后,此内容显示在div中。事实是,tinyMCE通常会添加具有绝对位置的样式,而某些样式会与其他Web应用程序一起破坏。
在测试时,我发现新的HTML 5
所以问题是:iframe srcdoc是否有其他选择,可以保留接收到的内容的所有样式并将其包含在div中?
您可以这样写入iframe的文档:
1 2 3 4 5 6 | 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(); |
eicto通过注释建议,可以使用jquery在就绪事件中填充iframe。为了将iframe的高度调整为内容的高度,必须应用一些肮脏的技巧,但是我最终使用的代码或多或少:
HTML
1 2 3 4 5 | <!-- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // 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('' +externalHtml +'' ); // 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); }); |
使用新的数据URI方案。
示例:
1 | var content ="<html></html>";document.getElementById("my_iframe_id").src ="data:text/html;charset=UTF-8," + content; |