2017-06-06 43 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); 
相關問題