如何应用CSS进行打印?

时间:2012-03-23 13:25:58

标签: javascript jquery css printing media

我正在尝试在我的某个页面中打印div但是在打印时我无法应用css。在样式标签内写入media =“print”不起作用。我该怎么办?

   <style type="text/css" media="print">
body
{
font-size:medium;
color:Black;
font-size:14px;
}
input 
{
margin:0px;
font-size:14px;


}
.grid
{
border-color:Gray;
border-width:1px;

}
.alan
{
border-style:none;

}

.grid1
{
border-color:Gray;
border-width:1px;
}
    </style>

4 个答案:

答案 0 :(得分:8)

使用以下内容:

<style type="text/css">
    @media print
    {
        body {
            /* styles */
        }
    }
</style>

答案 1 :(得分:3)

有很多方法:

首先:<style type="text/css"media="print">

第二:<style type="text/css"media="screen">

第三:

@media print 
 {
 body { margin: 0; background-image: none; font-size: 12pt; }
 }

希望这对你有帮助..

答案 2 :(得分:1)

您在原始邮件中执行的操作可以正常运行。这只是旧学校的做事方式。

需要注意的一点是,浏览器不会在打印模式下应用所有样式。它会选择并选择适合打印的样式。我还发现,如果你使用HTML 5 doctype,它会给你稍微不同的结果。

这是一个类似于您的简单示例,您可以在浏览器中尝试。

<!DOCTYPE html>
<html>
<head>
<style media="print">
.hideForPrint { display:none; }
.anotherSTyle { font-family: Verdana; text-decoration:underline; }
</style>
</head>
<body>
<div class="hideForPrint">Print This?</div>
<div class="anotherStyle">Another Style</div>
</body>
</html>

以下是Chrome(v19.0.1077.3 canary)打印预览的屏幕截图,您提到了用它来测试它。

enter image description here

答案 3 :(得分:0)

我正在使用Jquery Print Element 1.2插件仅打印div的内容。 这样,您就不需要为所有那些不想打印的元素设置css display:none。

我知道这不是你问题的直接答案,而是将其视为一种善意的建议。

示例:

$('SelectorToPrint').printElement();

这是我使用classNameToAdd选项的实现:

function printDiv(divToPrint) {

   $('#' + divToPrint).printElement(
        {
            printBodyOptions:
            {
                classNameToAdd: 'printarea'

            }
        }
   );

}

将插件添加到页面后,您可以在用户点击打印按钮/链接时调用上述功能。

<a href="#" onclick="javascript:printDiv('theIDofYourDiv')">Print part of the page</a>

您可以下载此插件并查找更多文档here