首页 > 解决方案 > 使用 css 样式打印 div

问题描述

我制作了一个脚本来打印一个 div,但是当我看到预览时,它并没有使用添加的 CSS 来“格式化”页面。

HTML部分:

<center>Do not print this</center>              
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
            <input type='button' value='Print' onClick='Print()' />

JS部分

function Print(){
     var corpo = document.getElementById('content').innerHTML;

     var a = window.open('','','width=640,height=480');
     a.document.open("text/html");
     a.document.write("<html><head><link rel=\"stylesheet\" href=\"./style.css\"></head><body><div class=\"print\">");
     a.document.write(corpo);
     a.document.write("</div></body></html>");
     a.document.close();
     a.print(); 
}

现场版:https ://codepen.io/Pop1111/pen/Vwabbzd

看起来它仅在之后加载 css。

有小费吗?

标签: javascript

解决方案


您的代码将创建无效的 HTML

尝试

function Print() {
  var corpo = document.getElementById('content').innerHTML;
  const html = [];
  html.push('<html><head>');
  // assuming the first stylesheet on the parent page - use a different selector if not
  // or use +location.protocol+'//'+location.host+'/style.css">'
  html.push('<link rel="stylesheet" href="' + document.querySelector("link[rel=stylesheet]").href + '">');
  html.push('</head><body onload="window.focus(); window.print()"><div>');
  html.push(corpo);
  html.push('</div></body></html>');
  console.log(html)
  /*  this will not work in the snippet - uncomment on your server
  var a = window.open('', '', 'width=640,height=480');
  a.document.open("text/html");
  a.document.write(html.join(""));
  a.document.close();
  */
}
<html>

<head>
  <link rel="stylesheet"  href="test.css" />
</head>

<body>
  <center>Do not print this</center>
  <div>Hi mom!</div>
  <center>Print this</center>
  <div id="content" class="print">Hi dad!</div>
  <input type='button' value='Print' onClick='Print()' />
</body>

</html>


推荐阅读