代码样例
html
<section id="myPrint" style="display: none">
<div class="print" ref="myPrint">
<h1>交易单据</h1>
<p>订单号:{{printData.orderNo}}</p>
<p>买家:{{printData.buyerName}} / {{printData.buyerPhone}}</p>
<p>脚环数量:{{printData.ankleNum}}</p>
<p>加工数量:{{printData.processNum}}</p>
<p>脚环费用:{{printData.anklePrice}} 元</p>
<p>加工费用:{{printData.processPrice}} 元</p>
<p>总价:{{printData.realPrice}} 元</p>
<p>下单时间:{{printData.createTime}}</p>
<p>操作员:{{user.realName}}</p>
<br>
<div class="no-print">不要打印我</div>
</div>
</section>
方法样例
posPrint (elementId) {
setTimeout(() => {
const el = document.getElementById(elementId)
const iframe = document.createElement('iframe')
let doc = null
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-10px;top:-10px;')
document.body.appendChild(iframe)
doc = iframe.contentWindow.document
// 打印的专有CSS样式,根据实际修改
doc.write('<style> .no-print { display: none} .print h1 { margin: 0px;text-align: center} .print p { margin: 0px;}</style>')
doc.write(el.innerHTML)
doc.close()
// 获取iframe的焦点,从iframe开始打印
iframe.contentWindow.focus()
iframe.contentWindow.print()
if (navigator.userAgent.indexOf('MSIE') > 0) {
document.body.removeChild(iframe)
}
}, 100)
}
使用传入dom的Id
this.posPrint('myPrint')