media print不会在chrome上应用样式,但在firefox中效果很好

时间:2015-11-09 17:06:04

标签: javascript jquery html css google-chrome

我有这个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中按预期工作:显示标题&amp;内容,在chrome中它只显示标题和空白页面(打印时相同)。

我已尝试同时使用@media print{}@media all{}但仍然无效。

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

我已尝试也更改了该功能并使用w.document.head.innerHtmlw.document.body.innerHtml - 仍然没有,与.write()具有相同的行为。

1 个答案:

答案 0 :(得分:0)

对我有用的是什么:

首先,我必须获取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();
}
相关问题