// 项目用的ts, 如果不是用ts 变量正常命名就行
const newWindow:any = window.open("打印窗口","_blank")
const printhtml:any = window.document.getElementById('printid');
if(newWindow.document.readyState=="complete"){
const stylArr:Array<any> = [];
Object.assign(stylArr,window.document.getElementsByTagName('style'));
newWindow.document.write(printhtml.innerHTML);
for(let i = 0; i < stylArr.length; i++){
const style = document.createElement('style');
style.innerHTML = stylArr[i].innerHTML;
newWindow.document.getElementsByTagName("head")[0].appendChild(style);
}
}
newWindow.print();
newWindow.close();
发现一个体验更好的写法:
<iframe id="iframe1" style="display: none"></iframe>
<div id="printid" >打印内容</div>
const iframe:any = document.getElementById("iframe1");//获取iframe的window对象
const iwindow:any = iframe.contentWindow;
// iwindow.document.body.innerText = "";//先清空iframe原先的内容
const printhtml:any = window.document.getElementById('printid');
if(iwindow.document.readyState=="complete"){
const stylArr:Array<any> = [];
Object.assign(stylArr,window.document.getElementsByTagName('style'));
// 内容加上去
iwindow.document.write(printhtml.innerHTML);
// 样式加上去
for(let i = 0; i < stylArr.length; i++){
const style = document.createElement('style');
style.innerHTML = stylArr[i].innerHTML;
iwindow.document.getElementsByTagName("head")[0].appendChild(style);
}
}
iwindow.print();
iwindow.close();