js---局部打印功能

发布时间 2023-04-03 13:50:29作者: 帅到要去报警

最近在开发一个项目,需要用到PC端打印的功能,很多都会去引入一个第三方的JS来做,其实打印功能很简单,调用浏览器的打印功能就可以实现。

代码示例:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>打印</title>
</head>
<body>

<button class="printBtn" id="printBtn">打印</button>

<h1>这块内容不需要打印</h1>
<!--startprint-->
<div class="print-content" style="background: red;">
    <h1>我是需要打印内容开始.....</h1>
    <img src="images/img1.jpg" alt="">
    <h1>我是需要打印内容结束.....</h1>
</div>
<!--endprint-->
<h1>这块内容不需要打印</h1>


<script type="text/javascript">
var printBtn = document.getElementById('printBtn');
printBtn.onclick = function(){
    doPrint();
}
function doPrint() {   
    bdhtml=window.document.body.innerHTML;   
    sprnstr='<!--startprint-->';   
    eprnstr='<!--endprint-->';   
    prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);   
    prnhtml=prnhtml.substring(0, prnhtml.indexOf(eprnstr));   
    window.document.body.innerHTML=prnhtml;  
    window.print();   
}

// 此处为图文打印
function printQrCode(idstr) {
  const imgUrlStr = 'https://weiliicimg9.pstatp.com/weili/l/905526294583705654.jpg';
  let iframe = document.createElement('IFRAME'),doc = null,img = new Image(); 
  img.src = imgUrlStr;
  iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
  document.body.appendChild(iframe);
  doc = iframe.contentWindow.document;
  doc.write('<h2>Print Pictures and Words</h2>');
  doc.body.append(img);
  doc.close();
  iframe.onload = function() { //解决图片显示不了的问题
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    document.body.removeChild(iframe);
  };
}
</script>

</body>
</html>

打完收工!