2017-12-27 1099 views
1

我有用於打印div內容的此javascript代碼。將css寫入javascript代碼does not work

function PrintElem() 
{ 
    var mywindow = window.open('', 'PRINT', 'height=600,width=800'); 

    mywindow.document.write('<html><head><title>' + document.title + '</title>'); 

    mywindow.document.write('<style type="text/css">' + @media print { 
    .no_print{ display:none;} 
    .fav_thumb{width:50%; height:50%; float:left} 
} + '</style>'); 

    mywindow.document.write('</head><body >'); 
    mywindow.document.write('<h2>' + document.title + '</h2>'); 
    mywindow.document.write(document.getElementById("favorite_items").innerHTML); 
    mywindow.document.write('</body></html>'); 

    mywindow.document.close(); // necessary for IE >= 10 
    mywindow.focus(); // necessary for IE >= 10*/ 

    mywindow.print(); 
    mywindow.close(); 

    return true; 
} 

我該怎麼寫一些打印CSS的新窗口,JavaScript打開?

+4

首先,您要添加的CSS(以'@ media'開頭)需要封裝在引號中。 –

+1

如果CSS引用正確,可以正常工作https://codepen.io/pjabbott/pen/XVMrOe –

回答

0

選項#1 - Inline Styles可能適用於您的目標。

此段使用內聯樣式的元素的HTML示例顯示在前一個鏈接上。

<p style="color:blue;font-size:46px;"> 
    I'm a big blue, <strong>strong</strong> paragraph 
</p> 

選項#2 - 內部樣式定義

選項#3 - 外部樣式文件

Styling HTML with CSS鏈接涵蓋了所有三(3)選項。