2021/04/30 window.print()不想打印页面某些部分

  • 背景:比如页面如下,点击打印按钮后,不需要按钮显示在打印页面上
    –页面在这里插入图片描述
    –打印预览框
    在这里插入图片描述

–有两种实现效果。
第一种,页面上‘打印’按钮一直存在
第二种,打印前按钮存在,打印后按钮不显示在页面上


  • 第一种:打印按钮一直在页面上,只是调用点击方法时不显示在打印预览框内
    –效果图
    在这里插入图片描述
    –代码
    主要是css设置,display: none;
//1.在template中  自定义样式noprint
<div class="print-footer noprint">
      <dm-button type="primary" @click="print">打 印</dm-button>
      <dm-button type="primary" @click="goPre">取 消</dm-button>
</div>

//2.在@media print中给noprint设置为 display: none;
@media print {
  body {
    -webkit-print-color-adjust: exact;
  }
  @page {
    margin: 0 !important; // 去除浏览器默认页眉页脚
    size: A4 landscape;
  }
  
  //不显示按钮
  .noprint {
    display: none;
  }
}

  • 第二种,点击打印弹出预览框后,按钮消失,不允许再次打印
    –代码
    主要是使用window.onafterprint()方法,在打印结束后会执行该方法内代码
//1.template 用printing来控制显隐
<div
      style="text-align: center; margin-top: 30px"
      :class="{ none: printting }"
    >
      <div>
        <button class="btn primary-btn" @click="goPrint">打印</button>
        <button class="btn second-btn" @click="goPre">取消</button>
      </div>
</div>

//2.data
data() {
    return {
      settleInfo: {}, //文字描述
      printting: false,
      imgCode: "", //二维码地址
    };
},

//3.methods中的打印方法
goPrint(){
      this.printting = true;
}

//4.window.onafterprint()方法 可以写在mounted中,也可以现在created中
mounted() {
    let that = this;
    //在页面打印后执行
    window.onafterprint = () => {
      that.printting = true;
       location.reload();
    };
},

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值