咱话不多说,这是比较完整的实现web打印与监听打印按钮的代码示例,希望可以帮助到你
toPrintPayment() {
//需要打印的内容
const printContent = document.querySelector('.paymentContain').outerHTML
const iframe = document.createElement('iframe')
iframe.setAttribute('style', 'position: absolute; width: 0; height: 0;')
document.body.appendChild(iframe)
const iframeDoc = iframe.contentWindow.document
//iframeDoc的样式
iframeDoc.write(`<style media="print">
@page {
size: auto;
margin: 0mm;
}
.PageNext{page-break-after: always;}
</style>`)
//iframeDoc的dom结构
iframeDoc.write(
'<div>' +
printContent +
'</div>'
)
let beforePrint = function () {
console.log('打印前')
}
//定义打印后事件
let afterPrint = function () {
console.log('打印后')
}
if (iframe.contentWindow) {
//打印前事件
iframe.contentWindow.onbeforeprint = beforePrint
//打印后事件
iframe.contentWindow.onafterprint = afterPrint
}
setTimeout(function () {
//.print()打开打印窗口
iframe.contentWindow?.print()
//这里的iframe只是为了给浏览器提供一个打印的对象,打印窗口打开后,记得从<body> </body>移除
document.body.removeChild(iframe)
}, 300)
},
如果这篇文章使你少走了一次弯路,记得点赞支持下哦