无法打印背景颜色(CSS解决方案)?

5

我正在尝试学习如何在Chrome中启用打印背景颜色的页面:

http://angularjs.org/为例。

主页是:

enter image description here

所以,如果我点击“打印”(ctrl+P)并勾选“背景颜色和图像”,它会显示未来要打印的背景颜色:

enter image description here

一切正常。

但是,如果我导航到另一个页面http://docs.angularjs.org/tutorial/step_02,也有背景颜色:

enter image description here

当我尝试打印时,我在预览窗格中没有看到颜色:

enter image description here

我的问题是:他们是怎么做到的?(或者更好的是,我如何使其打印背景颜色?)

我已经在这里阅读到,我应该使用-webkit-print-color-adjust:exact;

所以我通过Chrome开发者工具将其添加到了html中,但没有帮助。(当我再次点击ctrl+p时)

enter image description here

我应该在CSS中更改什么,以便它也打印背景颜色?

相关信息,搜索@media,在此处找到:

enter image description here

但我在那里没有找到任何相关信息。


你是否已经为“link”标签分配了媒体?将其设置为“all”或“print”作为值?因为大多数人将其设置为“screen”。 - Mr. Alien
@Mr.Alien 在底部添加了信息。 - Royi Namir
是的,我不是在问 Angular 的屏幕,因为我确定他们使用了它,那你的呢? - Mr. Alien
@Mr.Alien 嗯,既然我不知道他们是如何做到的,我就无法在自己的网站上测试了……? - Royi Namir
2个回答

6

好的,我觉得你没有理解我在评论中的意思,无论如何,这很简单,假设我有一个元素,比如:

<div class="blow"></div>

使用background属性设置为tomato,因此要使其生效,首先必须确保已设置media打印机媒体,例如:

@media print {
  /* Declarations go here */
}

或者

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

现在,你需要声明的是,在属性块中加入-webkit-print-color-adjust: exact;,如下所示:
@media print, screen { /* Using for the screen as well */
    .blow {
        height: 100px; 
        width: 100px; 
        background: tomato;
        -webkit-print-color-adjust: exact; 
    }
}

演示(仅适用于webkit浏览器,即Chrome / Safari)

在上面的演示中,您应该能够在Chrome的打印预览窗口中看到红色块。


正如您所评论的那样,对我有用。

enter image description here

或者

enter image description here


该支持有缺陷,有关属性的更多信息,请参见MDN

enter image description here

来自MDN:

Body元素背景不会被打印

目前,Chrome和Safari都不会打印body元素的背景。如果将此属性设置为exact,则仅适用于其后代。

Chrome剪裁图像错误

当剪切背景图像时(例如,使用背景图像精灵), 由于Chromium bug 131054,它们将 在使用-webkit-print-color-adjust: exact从Chrome浏览器打印时出现变形。纯色背景和未剪裁的背景图像(即宽度和高度小于 应用于其的元素)正确地打印。

外部链接

WebKit bug 64583:“WIP:添加CSS属性以控制单个元素的背景打印”
CSSWG wiki:“print-background”-提议标准化此 属性


1
我从来不知道 tomato 是一种有效的背景颜色。你让我开心了,外星人先生! - James Donnelly
@JamesDonnelly 那是我最喜欢的之一 :D - Mr. Alien

1
你的背景颜色可能被覆盖了。为了在打印时实现背景颜色,增加选择器的特异性或在语句中添加!important。连同-webkit-print-color-adjust: exact;一起使用,这应该适用于你:
@media print {
    .mycontainer {
        background-color: #000 !important;
        -webkit-print-color-adjust: exact;
    }
}

你是否添加了 !important 声明? - damian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接