繁体   English   中英

媒体打印不适用于chrome,但在firefox中效果很好

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

我有这个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文件的完整路径,并在link标签中设置媒体打印。

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM