如何使用jquery/JavaScript打印QR码

dsekswqp  于 12个月前  发布在  jQuery
关注(0)|答案(2)|浏览(150)

我只想打印QR code div而不是整页。
下面是我的代码:

<div id="qrcodeCanvas"></div> //Generating QR in this div

<a id="Html2Image" href="#qrcodeCanvas">Download</a>
<a id="mydiv" href="javascript:void(0);" onClick="PrintDiv();" >Print</a>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.qrcode.js"></script>
<script type="text/javascript" src="js/qrcode.js"></script>

<script>
function PrintDiv()
{

}
</script>

<script>
var id  =   'Content';
$('#qrcodeCanvas').qrcode(id);

var canvas = $('#qrcodeCanvas canvas');
var img = $(canvas)[0].toDataURL("image/png");

$("#Html2Image").attr("download", "QR_Code.png").attr("href", img); //Downloading QR image
</script>

字符串

mwkjh3gx

mwkjh3gx1#

@ImmanuelNL的答案应该有效,但它会破坏 * 一切 *。事件处理程序,代码中对元素的任何引用,一切都会被破坏。
相反,考虑这种非破坏性方法:

var tmp = document.createDocumentFragment(),
    printme = document.getElementById('printableArea').cloneNode(true);
while(document.body.firstChild) {
    // move elements into the temporary space
    tmp.appendChild(document.body.firstChild);
}
// put the cloned printable thing back, and print
document.body.appendChild(printme);
window.print();

while(document.body.firstChild) {
    // empty the body again (remove the clone)
    document.body.removeChild(document.body.firstChild);
}
// re-add the temporary fragment back into the page, restoring initial state
document.body.appendChild(tmp);

字符串

w3nuxt5m

w3nuxt5m2#

我也遇到了同样的问题,也遇到了这个解决方案。

<!DOCTYPE html>
<html>
<body>

  <div id="printableArea">
  <div id="qrcodeCanvas"></div>
</div>
<script>
function printDiv(divName) {
 var printContents = document.getElementById(divName).innerHTML;
 var originalContents = document.body.innerHTML;

 document.body.innerHTML = printContents;

 window.print();

 document.body.innerHTML = originalContents;
}
</script>
<input type="button" onclick="printDiv('printableArea')" value="print a qr!" />

</body>
</html>

字符串
来源:asprin

相关问题