window.print()

时间:2021-07-19 04:35:25

标签: 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;
}

更新:

也以这种方式检查。问题还是一样。

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

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

1 个答案:

答案 0 :(得分:3)

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

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

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