我编写了一个只打印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。
有什么建议吗?
发布于 2020-08-27 18:13:14
您的代码将创建无效的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>
发布于 2020-08-27 18:10:23
您的新文档未保存,因此没有预期的路径,因此CSS文件的相对引用找不到CSS。
要使其按预期工作,您需要将CSS引用更改为绝对引用,或者首先添加代码以保存新的HTML文件。
这只是你测试它的方式,还是你的生产版本也会这样工作?(新建文件,未保存,然后打印)。
您可以始终将实际的CSS本身插入到样式标签之间的新文档的头部,而不仅仅是对CSS文件的引用。试试看。
https://stackoverflow.com/questions/63613666
复制相似问题