打印样式表不会影响使用javascript

时间:2016-11-03 12:53:31

标签: javascript jquery html css

我已经在样式页面上声明了一个css并在css中打印出来像这样:

@page{
size :A4 landscape;
}

@media print {
table{
    border-collapse: collapse;
    font-family : serif;
    font-size : 10px;
}

table, th, td{
    border : 1px solid black;
}

th{
    text-align: center;
}

th:first-child{
    width: 10%;
}

td{
    background-color: red;
    color: blue;
}
}

这是css在浏览器中成功加载,我已经检查过了。

现在,我有一个像这样的js函数来管理打印页面:

function printDiv(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var originalContents = document.body.innerHTML;
  document.body.innerHTML = printContents;
  window.print();
  document.body.innerHTML = originalContents;

}

你知道,我有一张桌子,实际上,这是一个模态中的表格:

<table class="table table-bordered" id="table-struk">
<thead>
    <tr>
        <th style="width: 30%;">Item</th>
        <th style="width: 15%;">By</th>
        <th style="width: 18%;">Harga</th>
        <th style="width: 2%;">Qty</th>
        <th style="width: 30%;">Sub Total</th>
    </tr>

</thead>

<tbody>

    <tr><td>Gunting</td><td>Arif</td><td>85000</td><td>2</td><td>170000</td></tr></tbody>

<tfoot>
    <tr>
        <td colspan="2"></td>
        <td colspan="2">Jumlah Qty :</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2">Kasir 1</td>
        <td colspan="2">Total Pembayaran :</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2"></td>
        <td colspan="2">Cust. Bayar :</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2"></td>
        <td colspan="2">Kembali :</td>
        <td></td>
    </tr>
</tfoot>
</table>

这是使用此功能的按钮:

<button class="btn btn-success" onclick='
               w = window.open();
               w.document.write($("#modalContent").html());
               w.print();w.close();' 
      type="button">Print Test</button>

我的问题是,CSS不起作用, 页面现在可以打印,但不能使用上面的样式表单css, 任何帮助,非常感谢。

1 个答案:

答案 0 :(得分:1)

您应该使用media="print"

将css注入新窗口

使用下面的代码并将href值替换为css文件的路径

var w= window.open();
w.document.write('<html><head><title></title>');
w.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" media=\"print\"/>" ); //Inject CSS
w.document.write('</head><body >');
w.document.write($("#modalContent").html());//Your data
w.document.write('</body></html>');

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