外部 CSS 未在 window.print() 中加载

use*_*831 6 javascript jquery

我正在尝试打印页面的特定内容区域。CSS我的问题是我已经为此打印区域的内容创建了单独的文件。但该外部CSS在浏览器打印弹出窗口中无法工作(加载)。我确信文件路径是正确的。

这就是我尝试的方法:

function printReceipt(el) {
  var docHead = "<html>\
                  <head>\
                    <title></title>\
                    <link rel='stylesheet' href='css/receipt-print.css' type='text/css' media='print' />\
                  </head>\
                  <body>";
  var docFoot = " </body>\
                 </html>";
  var docBody     = document.getElementById(el).innerHTML;
  var defaultBody = document.body.innerHTML;
  document.body.innerHTML = docHead+docBody+docFoot;
  //document.close(); 
  //window.focus(); 
  //setTimeout(function() {
  window.print();
  document.body.innerHTML = defaultBody;
  //}, 1000);    
  //return true;
}
Run Code Online (Sandbox Code Playgroud)

更新:

也按此方法检查。问题还是一样。

function printReceipt(el) {
  var w = window.open();
  w.document.write('<html><head><title></title>');
  w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
  w.document.write('</head><body >');
  w.document.write(document.getElementById(el).innerHTML);
  w.document.write('</body></html>');

  w.document.close();
  w.focus();
  w.print();
  w.close();
  return true;
}
Run Code Online (Sandbox Code Playgroud)

任何想法和建议将不胜感激。

a.m*_*ola 5

问题是您在打印页面时没有等待样式和资源加载。

您应该等待页面加载后再尝试打印,或者您可以尝试使用内联样式。

function printReceipt(el) {
  var w = window.open();

  w.document.write('<html><head><title></title>');
  w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
  w.document.write('</head><body >');
  w.document.write(document.getElementById(el).innerHTML);
  w.document.write('<script type="text/javascript">addEventListener("load", () => { print(); close(); })</script></body></html>');

  w.document.close();
  w.focus();
}
Run Code Online (Sandbox Code Playgroud)