1、其原理就是通過給打印dom設置id值,通過新建iframe,將需要打印的dom結構塞進iframe中,這樣不會跳轉頁面,也不會刷新頁面,防止本頁面內容還沒有處理完邏輯,而發生不必要的跳轉,導致邏輯被刷新。
2、這要就會造成一個問題,引入外部樣式出現問題,只能插入標籤樣式。
代碼如下:
function prints(){
const el = document.getElementById('box');
const iframe = document.createElement('iframe');
let doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;background:blue');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的專有CSS樣式
doc.write("<html><head>");
//引入外部樣式沒有起作用
doc.write(`<link rel='stylesheet' type='text/css' href='./css/print.css'>`);
doc.write("</head><body>");
doc.write('<div style="width:100%;height:auto;min-width:1100px;margin:0px auto;"align="center">'+el.innerHTML+'</div>');
doc.write(el.innerHTML);
doc.write("</body></html>");
var ys="html,body{height:100%}h2{color:red}";
var style=document.createElement("style");
//該樣式生效
style.innerText=ys;
doc.getElementsByTagName("head")[0].appendChild(style);
doc.close();
// 獲取iframe的焦點,從iframe開始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
iframe.contentWindow.close();
if (navigator.userAgent.indexOf("MSIE") > 0)
{
document.body.removeChild(iframe);
}
}