首先上代碼:
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 中的寫法不一樣, 具體請看代碼.