浏览器调用print实现部分打印的两种方法

2023-02-02  本文已影响0人  软践

替换body的内容为要打印的内容,然后再从新刷新页面

const old = window.document.body.innerHTML //备份原来的页面
window.document.body.innerHTML = ''
window.document.body.appendChild(/* 将你要打印的内容附加到这 */)
window.print() //调用print()函数时,会跳出打印预览的界面,如下的代码被阻塞,关闭预览界面后继续执行
window.document.body.innerHTML = old
window.location.reload() //从新加载旧页面

将打印内容放到新窗口打印,打印结束后关闭新窗口

const newWindow = window.open("打印窗口", "_blank")
const docStr = '<div>test</div>'  //须要打印的内容
newWindow.document.write(docStr)
const styles = document.createElement("style")
styles.setAttribute('type', 'text/css') //media="print"
styles.innerHTML = ''
newWindow.document.getElementsByTagName('head')[0].appendChild(styles)
newWindow.print()
newWindow.close()

详见原文 http://oejia.net/blog/2022/05/30/browser_print.html

本文由博客一文多发平台 OpenWrite 发布!

上一篇 下一篇

猜你喜欢

热点阅读