一般来说,我反对使用iframe,但它解决了我的一个特殊问题.
问题是我在一个网页上有一个tinyMCE编辑器.在用户使用此编辑器制作内容之后,内容将作为HTML发送到Web应用程序.然后,此内容将显示在div中.事实上,tinyMCE经常添加具有绝对位置的样式以及与Web应用程序的其余部分分离的内容.
在测试时我发现新的HTML 5 iframe srcdoc="<p>Some HTML</p>"并且seamless="true"非常适合我的情况.它看起来很无缝,内容风格和我的风格完好无损.遗憾的是,我现在看到Android尚不支持HTML5 srcdoc属性(http://w3schools.com/html5/tryit.asp?filename=tryhtml5_iframe_srcdoc在chrome和android浏览器中产生不同的结果).
所以问题是:是否有任何替代iframe srcdoc将保留所有接收内容的样式并将其包含在div中?
Chr*_*die 19
您可以像这样写入iframe的文档:
var iframeDocument = document.querySelector('#foo').contentWindow.document;
var content = '<html></html>';
iframeDocument.open('text/html', 'replace');
iframeDocument.write(content);
iframeDocument.close();
Run Code Online (Sandbox Code Playgroud)
Sin*_*dre 10
正如eicto通过评论所建议的那样,jquery可用于在准备事件中填充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>
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)