我有一个简单的桌子,下面有一个按钮。这是在我的jsp的主体部分中,如下所示:
<div id="myDivForPrint">
<table class="t1">
<tbody>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
</div>
<button onclick="printDiv()">Print</button>
以下是带有@media规则的CSS,用于格式化表格。 CSS在我的jsp的头部:
@media print,screen{
table.t1 {
margin: 1em auto;
border-collapse: collapse;
font-family: Arial, Helvetica, sans-serif;
}
.t1 th, .t1 td {
padding: 4px 8px;
}
.t1 thead th {
background: #4f81bd;
text-transform: lowercase;
text-align: left;
font-size: 15px;
color: #fff;
}
.t1 tr {
border-right: 1px solid #95b3d7;
}
.t1 tbody tr {
border-bottom: 1px solid #95b3d7;
}
.t1 tbody tr:nth-child(odd) {
background: #dbe5f0;
}
.t1 tbody th, .t1 tbody tr:nth-child(even) td {
border-right: 1px solid #95b3d7;
}
.t1 tfoot th {
background: #4f81bd;
text-align: left;
font-weight: normal;
font-size: 10px;
color: #fff;
}
.t1 tr *:nth-child(3), .t1 tr *:nth-child(4) {
text-align: right;
}
}
</style>
以下是用于打印包含我的表格的div的javascript函数。它在我的jsp的主体部分中:
<script type="text/javascript">
function printDiv()
{
var divToPrint=document.getElementById("myDivForPrint");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.document.close();
newWin.document.focus();
newWin.print();
newWin.close();
}
</script>
该页面在屏幕上格式化良好。但是,当我单击“打印”按钮并以xps文档的形式打印页面时,所有CSS格式都会丢失,并且仅打印表的内容,这看起来确实很糟糕。
我究竟做错了什么 ?我正在使用IE8,并且无法移至其他浏览器或IE的较新版本。
最佳答案
您可以在样式表中为屏幕和打印媒体使用不同的样式,即
@media screen
{
table.test {
font-family:"Times New Roman",Georgia;
font-size:10px;
// more
}
}
@media print
{
table.test {
font-family:Verdana, Arial;
font-size:10px;
// more
}
}
当您打印表格时,将仅应用在打印介质中定义的样式。
Click This for more
关于javascript - @media print CSS无法在打印时格式化表格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32853160/