媒体打印;t在chrome上应用样式,但在firefox中效果完美

media print doesn't apply style on chrome, but in firefox works perfectly

本文关键字:firefox 但在 完美 样式 应用 打印 chrome 媒体      更新时间:2023-09-26

我有这个js函数:

function print(title, htmlPrint) {
   var w = window.open('', '', 'width=600,height=750');
   w.document.title = title;
   w.document.write('<link rel="stylesheet" type="text/css" href="print.css" />');
   w.document.write(htmlPrint);
   w.document.close(); // needed for chrome and safari
   w.print();
   w.close();
   return false;
}

在css中,我有这样的东西:

@media print, screen{ 
.....
}

在firefox作品如预期:显示标题&内容,在chrome中,它只显示标题和空白页(打印时也是如此)。

我也尝试过使用@media print{}@media all{},但仍然不起作用。

我也尝试过<link... />中添加media="print",这样做会加载css,但不会将任何css应用于页面。

我也尝试过更改函数并使用w.document.head.innerHtmlw.document.body.innerHtml——仍然没有,具有与.write()相同的行为。

对我有用的东西:

首先,我必须获得css文件的完整路径,并在链接标记中设置媒体打印。

if (/chrome/i.test(navigator.userAgent)) {
     w.document.write('<link rel="stylesheet" type="text/css" href="' + location.protocol + '//' + location.host + (new String(location.pathname.substring(0, location.pathname.lastIndexOf("/")))) + '/print.css" media="print" />');
}else{
     w.document.write('<link rel="stylesheet" type="text/css" href="print.css" />');
}

然后它仍然不能正常工作,我刚刚发现w.close()会给chrome带来问题。

if (/chrome/i.test(navigator.userAgent) === false) {
    w.close();
}