【问题标题】:Place HTML and CSS in my iframe using javascript使用 javascript 在我的 iframe 中放置 HTML 和 CSS
【发布时间】:2017-06-06 16:06:15
【问题描述】:

我正在一个小项目中构建一个 html 预览工具,并且我正在尝试找到将 html 和将样式化该 html 的 css 放置在 iframe 中的最佳方法。

我能够创建 iframe 并将我的 div 的 html 内容放入其中。到目前为止,这似乎工作正常in this fiddle

$(function() {

    var $html = $("#html").html();
    var $frame = $('<iframe>');
        $('body').html( $frame );

    var doc = $frame[0].contentWindow.document;
    var $framehtml = $('html',doc);
        $framehtml.html($html);

});

但是如何将 css 添加到该 iframe 的头部?例如,将您在小提琴中看到的 .mobile 类添加到 iframe 的头部,这样当 iframe 达到 500px 的宽度时,图像就会被隐藏?

编辑:我不想注入 css 样式表。我宁愿在头部创建一个标签,并将您看到的 css 放在小提琴中。

【问题讨论】:

标签: javascript jquery html css iframe


【解决方案1】:

@FRAN 和@APAD1 是对的,这是重复的。我能够使用这些答案来创建我自己的updated fiddle

    var $head = $("#myframe").contents().find("head");                
    $head.append($("<style/>", 
                   {type: "text/css" }));


    var $style = $("#myframe").contents().find("style");                
    $style.append($css);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-15
    • 2011-06-07
    • 2011-10-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多