图片授权基于 www.pixabay.com 相关协议
最近项目中有「打印」需求,要求把页面中一部分元素通过「打印机」打印出来,所以研究了一下 Print 打印功能。
Opens the Print Dialog to print the current document.
打开「打印对话框」打印当前文档
In most browsers, this method will block while the print dialog is open. However in more recent versions of Safari, it may return immediately.
在大多数浏览器,打开「打印对话框」时会阻塞其他方法。
https://developer.mozilla.org/en-US/docs/Web/API/Window/print
<button id=\\\"printFn\\\" onclick=\\\"printFn()\\\">打印</button>
<script>
function printFn(){
window.print(); //直接打印
}
</script>
<style>
//只要获取到操作打印的动作就会执行下方 css
@media print{
.print{color: red;}
}
</style>
The beforeprint event is fired when the associated document is about to be printed or previewed for printing. 这个 beforeprint 事件,在当文档将要打印或预览打印时会触发。 https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeprint_event
window.addEventListener(\\\'beforeprint\\\', (event) => {
console.log(\\\'Before print\\\');
});
The afterprint event is fired after the associated document has started printing or the print preview has been closed.
这个 afterprint 事件,在文档开始打印或预览打印关闭后触发。
https://developer.mozilla.org/en-US/docs/Web/API/Window/afterprint_event
window.onafterprint = (event) => {
console.log(\\\'After print\\\');
};
window.matchMedia(\\\'print\\\')
The Window interface\\’s matchMedia() method returns a new MediaQueryList object representing the parsed results of the specified media query string.
Window 的接口 matchMedia() 方法可以返回一个新的 MediaQueryList 对象,这个对象是媒体查询字符串的解析结果。
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
let matchPrint = window.matchMedia(\\\"print\\\");
matchPrint.addListener(res => {
if (res.matches) {
console.log(\\\"open\\\");//打开了「打印对话框」
} else {
console.log(\\\"close\\\");//关闭了「打印对话框」
}
});
if (res.matches) {
let _id = document.getElementById(\\\'someId\\\');
_id.style.display = \\\'none\\\';
console.log(\\\"open\\\");//打开了「打印对话框」
}
在打印对话框中,可以选择右侧的「更多设置」中,取消「页眉页脚」,即可解决。
推荐阅读
JavaScript 的装箱和拆箱
参考资料:
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34596.html