首先上代码:
function PrintDiv(ID) {
var needPrint = document.getElementById(ID);
var win = window.open("");
win.document.write('<html><head><link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />'
+ '<link href="css/app.css" rel="stylesheet" />'
+ '<link href="PWA.styles.css" rel="stylesheet" /></head><body>'
+ needPrint.outerHTML + '</body>'
+ "</html>");
win.document.close();
//Chrome
if (navigator.userAgent.indexOf("Chrome") != -1) {
win.onload = function () {
win.document.execCommand('print');
win.close();
}
}
//Firefox
else {
win.print();
win.close();
}
}
打印div的几种写法
法一: 替换当前页面
function PrintDiv(ID){
var needPrint = document.getElementById(ID).innerHTML;
var old = document.body.innerHTML;
document.body.innerHTML=needPrint;
window.print();
document.body.innerHTML=old;
}
此法能很好的保留样式, 但是在Blazor中存在一个问题: 调用以后页面中所有的按钮都会失效.
问题的产生应该与Blazor框架的底层机制有关, 在此不深究.
法二: 在新页面中打印
此法需要注意一点: 如果需要保留样式, 需要将CSS引用一并写入新页面, 需要等待页面加载完成后才能开始打印, 否则打印结果不带样式.
等待页面加载完成在 Firefox 和 Chrome 中的写法不一样, 具体请看代码.