function printPartial(dom) {
if (!dom) return;
let copyDom = document.createElement('span');
const styleDom = document.querySelectorAll('style, link, meta');
Array.from(styleDom).forEach(item=> {
copyDom.appendChild(item.cloneNode(true));
});
copyDom.appendChild(dom.cloneNode(true));
const htmlTemp = copyDom.innerHTML;
copyDom = null;
const iframeDom = document.createElement('iframe');
const attrObj = {
height: 0,
width: 0,
border: 0,
wmode: 'Opaque',
};
const styleObj = {
position: 'absolute',
top: '-999px',
left: '-999px',
};
Object.entries(attrObj).forEach(([key, value])=> iframeDom.setAttribute(key, value));
Object.entries(styleObj).forEach(([key, value])=> iframeDom.style[key] = value);
document.body.insertBefore(iframeDom, document.body.children[0]);
var iframedocument = iframeDom.contentDocument;
var iframeWindow = iframeDom.contentWindow;
iframedocument.open();
iframedocument.write(`<!doctype html>`);
iframedocument.write(htmlTemp);
iframedocument.close();
iframeWindow.onload = function() {
iframeWindow.focus();
iframeWindow.print();
document.body.removeChild(iframeDom);
}
注意:一定要在 iframe 里 windows 对象内容加载成功之后再去打印,iframe 的 print 方法是个阻塞的方法,类似 alert,会阻塞页面后续加载。