javascript打印页面

打印方法:window.print()

打印前:window.onbeforeprint

打印后:window.onafterprint

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>打印</title>
    <style>
      /* 去除浏览器默认页眉页脚 */
      @media print {
        @page {
          margin: 0;
        }
        body {
          margin: 1cm;
        }
      }
    </style>
  </head>
  <body>
    <div>不打印的内容</div>
    <div class="print">
      <span>打印区域1</span>
      <p>打印区域2</p>
      <div>打印区域3</div>
    </div>
    <input type="button" value="打印" onclick="printHandle()" />
  </body>

  <script>
    function printHandle() {
      let body_box = window.document.body.innerHTML
      let print_box = document.querySelector('.print').innerHTML
      // 打印前
      window.onbeforeprint = () => {
        console.log('开始打印')
        window.document.body.innerHTML = print_box
      }
      // 打印后
      window.onafterprint = () => {
        console.log('结束打印')
        window.document.body.innerHTML = body_box // vue使用此方法第二次点按钮会失效
        // location.reload() // 可使用刷新解决vue按钮失效问题
      }
      // 打印
      window.print()
    }
  </script>
</html>

参考:前端网页打印window.print()-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_41579327/article/details/129315698