Javascript 设置打印样式表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5359943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:55:49  来源:igfitidea点击:

Javascript set print stylesheet

javascriptcssstylesheet

提问by Leticia Meyer

How would I modify the style of an object for the print stylesheet? I'm using jQuery, if that's of any help.

我将如何修改打印样式表的对象样式?我正在使用 jQuery,如果这有帮助的话。

I basically want to set a css property of an object, but have that property apply for print only, not screen. e.g. $('#myobject').css('background','white','print');

我基本上想设置一个对象的 css 属性,但该属性仅适用于打印,而不适用于屏幕。例如$('#myobject').css('background','white','print');

采纳答案by Paul Sham

This question is a little vague, so I'm not sure if I'm following what you're trying to do. Are you trying to dynamically modify the style of an object for print?

这个问题有点含糊,所以我不确定我是否在关注你想要做的事情。您是否尝试动态修改打印对象的样式?

If so, you can try adding styles to the head, like the following:

如果是这样,您可以尝试向头部添加样式,如下所示:

$('head').append('<style type="text/css" media="print">Whatever styles</style>');

回答by Haochi

You are going to need to add a CSSStyleSheetto document.styleSheetsand set the mediatype to print. https://developer.mozilla.org/en/DOM/stylesheet

您将需要添加一个CSSStyleSheettodocument.styleSheets并将media类型设置为print. https://developer.mozilla.org/en/DOM/stylesheet

回答by Joel Friedlaender

Create a print css file in your application like this:

在您的应用程序中创建一个打印 css 文件,如下所示:

Filename: print.css

文件名:print.css

#myobject {
background-color: white;
}

In your application header, include the file like this:

在您的应用程序标头中,包含如下文件:

<link rel="stylesheet" href="print.css" type="text/css" media="print" />

Note the media="print"when I included the stylesheet. This will apply your white background to the object only when printing.

当我包含样式表时,请注意media="print"。这只会在打印时将白色背景应用于对象。

回答by Mark Eirich

I think the only way to do this is set a special ID or class on the element, then define a style for that in your print stylesheet:

我认为唯一的方法是在元素上设置一个特殊的 ID 或类,然后在你的打印样式表中定义一个样式:

<html><head>
    <style type="text/css" media="print">
    .print_blue { color: blue; }
    </style>
</head><body>

<span id="to_change">This is black text.</span>
<a href="#" onclick="jQuery('#to_change').addClass('print_blue');return false">Click here</a>
to change it to blue for printing.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</body></html>