javascript - 使用 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。
有小费吗?
解决方案
您的代码将创建无效的 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>
推荐阅读
- postgresql - 自动提交在 postgresql 和 psycopg2 中是什么意思?
- laravel - laravel 集合对象中的新属性以 JSON 形式返回
- powershell - 如何检查选择了 ValidateSet 的哪个值而不在“if”块中重新键入该值作为文字?
- javascript - JS 和 HTML 中的数独
- stream - Flutter:将两个 Stream 流式传输到一个屏幕中?
- css - 弯曲孩子的孩子占据了所有的空间
- ruby-on-rails - ActiveStorage 变体组合
- php - 反垃圾邮件 php 问题
- python - scipy.optimize.root 用完所有内存
- c++ - 使用 std::thread 使用 Visual Studio 2015 执行 lambda 函数时崩溃