簡體   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