window.print()实现打印指定内容——功能实现

HTML

<!-- 打印的内容会生成两页纸 -->
 <div id="report">
 	<h1>..</h1>  <----重点
    <div>..</div>
</div>  

JS

function printpage() {
    // 打印的整体思路是:获取body的内容进行存储,然后获取打印区域的内容填充到body中,进行打印,打印完成后,再将之前存储的body内容重新赋值给body即可。
    // windown.print()默认打印的内容是body的内容。
    let oldStr = window.document.body.innerHTML;
    let newStr = document.getElementById('printContent').innerHTML;
    window.document.body.innerHTML = newStr;
    window.print();
    window.document.body.innerHTML = oldStr;
}

上面的方法是百度的,但我试了,好像行不通,大伙可以自行验证试试
下面是方法思路

<template>
  <div id="home">
    <Viewer></Viewer>
    <div id="allContent">
      <PopupAttribute></PopupAttribute>
      <LayerManage></LayerManage>
      <MenuList></MenuList>
      <BottomBar></BottomBar>
    </div>
  </div>
</template>
// 执行打印的时候,把不需要的内容进行隐藏,打印完后再显现
printPage() {
  let content = document.querySelector("#allContent");
  content.style.display="none";
  window.print();
  content.style.display="block";
}


样式问题

//就是执行print后,样式在这里可以自定义
//在style中,使用@media print{}
//不要嵌套写
//如果使用less,scss 是不会生效的
//只能使用css语言格式, 就是不能像less、scss嵌套写
@media print {
  div{
    font-size:12px;
    ···
  }
  ···
}
posted @ 2022-08-27 18:56  槑孒  阅读(547)  评论(0编辑  收藏  举报