【问题标题】:How to add CSS on the print page?如何在打印页面上添加 CSS?
【发布时间】:2019-08-21 06:33:21
【问题描述】:

我想为要打印的部分添加样式。

 let popupWinindow
 let innerContents = this.printDiv.nativeElement.innerHTML;
 popupWinindow = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
 popupWinindow.document.open();
 popupWinindow.document.write('<html><head><link href="styles.css" rel="stylesheet" type="text/css"></head><body onload="window.print();">' + innerContents + '</html>');
 popupWinindow.document.close();

当我在样式标签内部添加样式时,一切正常。 但是当我尝试以外部方式添加它时,它不适用于 printDiv。

这是我在控制台中遇到的错误。

Refused to apply style from 'http://localhost:4200/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

【问题讨论】:

  • 查看post
  • 尝试下载localhost:4200/styles.css,在浏览器地址栏输入,确认得到的是css文档而不是404 html错误页面
  • 我收到一个错误页面,我该怎么办?所以,它会自动获得访问权限
  • 您应该使用样式表的完整绝对路径(包括协议和域)

标签: javascript angular angular7 angular8


【解决方案1】:

对于打印,您应该添加一个媒体查询print

@media print {
   // Your styles
}

还要检查styles.css 文件的路径。例如在这里你可以找到更多信息Stylesheet not loaded because of MIME-type

【讨论】:

  • 我的问题是,它没有直接采用styles.css。
  • 我已经参考了这个链接,我的 css 文件名为“styles.css”,它在文件夹 src/styles.css 下
  • 嗯,你能在stackblitz上重现这个问题吗?
【解决方案2】:

打开的窗口与打开的窗口有些无关。它不知道您的文件的路径以及域和协议。您应该在代码中将完整的绝对 URL 插入到您的样式表中。

所以如果你的样式表文件位于https://example.com/path/to/file/style.css,你应该使用

 popupWinindow.document.write('<html><head><link href="https://example.com/path/to/file/style.css" rel="stylesheet" type="text/css"></head><body onload="window.print();">' + innerContents + '</html>');

请参阅https://codepen.io/HerrSerker/pen/70cdc072c09f04b850b67febe7ef0f34 以获得工作演示

你可以在JS中动态获取到你的html文件的路径信息

location.protocol + "//" + location.host + location.pathname.replace(/\/(?!.*\/).*$/, '/')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2013-05-13
    • 1970-01-01
    • 2023-03-24
    • 2017-04-08
    • 2012-01-10
    相关资源
    最近更新 更多