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);
}
}