@Media 打印样式不适用

Vug*_*yev 1 html javascript css sass

Stackblitz: https: //stackblitz.com/edit/angular-xvdy1q
我想打印特定的div.

<div id="forPrint" (click)="onPrint('23')">
  <div id="printable">
    <div class="box">

    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript 代码:

onPrint(url) {
  this.mode = 'print';
  const mywindow = window.open('', 'PRINT', 'height=400,width=600');

  mywindow.document.write(`<html><head><title>${document.title}</title>`);
  mywindow.document.write('</head><body >');
  mywindow.document.write(`<h1> www.${url}</h1>`);
  mywindow.document.write(document.getElementById('forPrint').innerHTML);
  mywindow.document.write('</body></html>');
  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}
Run Code Online (Sandbox Code Playgroud)

风格:

@media print {
  html,
  body {
    height: 100% !important;
    width: 100%!important;
    h1 {
      color: #1c7430;
    }
  }
  #printable {
    display: flex!important;
    justify-content: center!important;
    align-items: center!important;
    height: 100% !important;
    width: 700px!important;
  }
  .box {
    width: 100px!important;
    height: 100px!important;
    background: green!important;
  }
}
Run Code Online (Sandbox Code Playgroud)

但打开打印对话框后,该框不显示。因此没有应用任何样式,例如h1, .box。有什么问题吗?提前致谢。

Tur*_*nip 5

您需要以某种方式将 CSS 注入新页面。

这里我创建一个style标签并直接添加CSS。您也可以链接到样式表:

function onPrint(url) {
  this.mode = 'print';
  const mywindow = window.open('', 'PRINT', 'height=400,width=600');

  const styles = `html,
      body {
        height: 100% !important;
        width: 100%!important;
      }
      h1 {
          color: #1c7430;
      }
      #printable {
        display: flex!important;
        justify-content: center!important;
        align-items: center!important;
        height: 100% !important;
        width: 700px!important;
      }
      .box {
        width: 100px!important;
        height: 100px!important;
        background: green!important;
      }`

  mywindow.document.write(`<html><head><title>${document.title}</title>`);
  mywindow.document.write(`<style>${styles}</style>`)
  mywindow.document.write('</head><body >');
  mywindow.document.write(`<h1> www.${url}</h1>`);
  mywindow.document.write(document.getElementById('forPrint').innerHTML);
  mywindow.document.write('</body></html>');
  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}
Run Code Online (Sandbox Code Playgroud)

JSFiddle 演示