打印网页

本文介绍了一种在Vue.js中实现局部网页打印的方法,通过使用iframe元素和其contentWindow.print()方法,可以将页面中特定部分的内容进行打印。文章提供了完整的代码示例,包括如何克隆需要打印的内容并将其插入到iframe中。

记:打印局部网页,借助iframe的print方法

代码如下

<template>
  <div>
    <div id="content">
      <img src="../assets/logo.png">
      <h1>{{ msg }}</h1>
    </div>
    <iframe id="iframe" style="display: none"></iframe>
    <button v-on:click="print">打印</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    print: function () {
      window.document.querySelector('#iframe')['contentWindow'].document.body.innerHTML = '';
      window.document.querySelector('#iframe')['contentWindow'].document.body.appendChild(window.document.querySelector('#content').cloneNode(true));
      window.document.querySelector('#iframe')['contentWindow'].print()
    }
  }
}
</script>

效果如下:

点击打印效果如下:

至于打印的样式就自己调整了,要注意的是,外部文件的样式无法在打印时引入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值