注意:
1、推薦使用內(nèi)聯(lián)樣式,或iframe中創(chuàng)建樣式表
2、寬度使用px而不用%车伞,打印發(fā)現(xiàn)被放縮時(shí)檢查樣式,控制好寬度去排查都會(huì)得到解決
3喻喳、盡量使用es5語(yǔ)法另玖,防止低版本瀏覽器不兼容
4、圖片使用base64,防止圖片資源還在加載中但是已經(jīng)執(zhí)行了打颖砺住(onload方法可解決圖片不顯示問(wèn)題谦去,但是低版本瀏覽器可能不執(zhí)行onload)
場(chǎng)景一:
需要打印的dom外層無(wú)iframe嵌套:
//id為打印的節(jié)點(diǎn)
const printDomContentByIframe = id => {
const el = document.getElementById('id');
const iframe = document.createElement('iframe');
let doc = null;
iframe.id = 'printIframe';
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
//注意這里取的是innerHTML,ref賦予對(duì)象別弄錯(cuò)
doc.write(el.innerHTML);
doc.close();
// 獲取iframe的焦點(diǎn)蹦哼,從iframe開(kāi)始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
//打印完畢后移除iframe很重要
iframe.parentNode.removeChild(iframe);
};
場(chǎng)景二:
需要打印的dom外層有iframe嵌套, 此時(shí)document.getElementById取不到節(jié)點(diǎn):
- src同域
//contentWindow 所有瀏覽器都支持鳄哭,包括舊版本的IE
document.getElementById('myframe').contentWindow.document.getElementById('x')
2.src不同域
//el為dom實(shí)例,使用ref直接傳入dom實(shí)例
const printDomContentByIframe = el => {
const iframe = document.createElement('iframe');
let doc = null;
iframe.id = 'printIframe';
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
//注意這里取的是innerHTML翔怎,ref賦予對(duì)象別弄錯(cuò)
doc.write(el.innerHTML);
doc.close();
// 獲取iframe的焦點(diǎn)窃诉,從iframe開(kāi)始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
//打印完畢后移除iframe很重要
iframe.parentNode.removeChild(iframe);
};