JS利用iframe 局部打印
2020-11-18 本文已影响0人
木易先生灬
// 打印
const handlePrint = () => {
console.log('打印一下!')
// 获取打印内容
let Pdiv = document.getElementById('printBody')
// 创建iframe
let iframe = document.createElement('IFRAME')
iframe.setAttribute(
'style',
'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'
)
document.body.appendChild(iframe)
let doc = iframe.contentWindow.document
// 打印时去掉页眉页脚
doc.write('<style media="print">@page {size: auto; margin: 0mm; }</style>')
// 打印内容放入iframe中
doc.write(Pdiv.innerHTML)
let ys = 'html,body{height:auto}'
let style = document.createElement('style')
style.innerText = ys
doc.getElementsByTagName('head')[0].appendChild(style)
doc.close()
// 开始打印iframe内容
iframe.contentWindow.focus()
iframe.contentWindow.print()
if (navigator.userAgent.indexOf('MSIE') > 0) {
//打印完删除iframe
document.body.removeChild(iframe)
}
}