我试图阻止用CSS隐藏/显示一堆元素,而只是在打印时渲染它们,为此我使用这种模式:
const beforePrint = () => { console.log('beforePrint') };
const afterPrint = () => { console.log('afterPrint') };
if (window.matchMedia) {
const mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener((mql) => {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.addEventListener('beforeprint', this.handleBeforePrint);
window.addEventListener('afterprint', this.handleAfterPrint);
console.log
按预期触发,但是当我渲染元素而不是console.log
时,它仅在用户执行 Ctrl + p时有效而不是在触发window.print
时。
以下是我的示例https://pw74zpl44x.codesandbox.io/和代码(在React中,但无关紧要)https://codesandbox.io/s/pw74zpl44x