2017-06-06 45 views
-2

我正在构建一个小型项目中的html预览工具,并且试图找到放置html和CSS的最佳方式,将在iframe中设置html样式。将HTML和CSS放置在我的iframe中使用javascript

我可以创建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放在小提琴中。

+0

的可能的复制[添加CSS来的iFrame](https://stackoverflow.com/questions/6960406/add-css-to-iframe) – APAD1

+0

[如何将CSS应用到iframe?](https://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe) – Nope

回答

0

@ 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); 
相关问题