【问题标题】:Alternatives to iframe srcdoc?iframe srcdoc 的替代品?
【发布时间】:2012-10-24 05:52:25
【问题描述】:

通常我反对使用 iframe,但它解决了我的一个特定问题。

问题是我在网页上有一个 tinyMCE 编辑器。用户使用此编辑器制作内容后,内容将作为 HTML 发送到 Web 应用程序。这个内容然后显示在一个 div 中。问题是 tinyMCE 经常添加 绝对位置样式 以及与网络应用程序的其余部分相冲突的东西。

测试时我发现新的 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 中?

【问题讨论】:

标签: css html iframe


【解决方案1】:

您可以像这样写入 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();

【讨论】:

    【解决方案2】:

    使用新的Data URI Scheme。 示例:

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

    【讨论】:

    【解决方案3】:

    正如 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>
    

    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);
    });
    

    【讨论】:

    • 如果任何内容不受信任且未经过沙盒处理,请不要这样做——如果用户粘贴代码 sn-ps...
    猜你喜欢
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多