matchMedia&在window.print

时间:2018-02-05 16:54:08

标签: javascript

我试图阻止用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

0 个答案:

没有答案