:::info window.print()打印其实打印的是整个当前网页 :::
主体思路是要把打印的区域截取出来,把当前的页面重构,截取完恢复页面
<body><div class="warp"><input id="qrcode_text" type="text" style="" value="生成二维码"><div class="header">二维码收款</div><div class="content"><p>无需加好友,扫二维码向我付钱</p><div class="ewm" id="erweima"></div><div class="footer_text"><span class="left_" >设置金额</span><span class="right_" id="dy">打印收款码</span></div></div><div class="footer">收款小账本</div></div><!--startprint--><div class="newWarp"><div class="content"><div class="header_"><div class="logo">推荐使用微信</div><div class="img_" id="img_"><img src=""></div><div class="logo" id="logo_text">匆匆那年</div></div><div class="footer_d"></div></div><!--endprint--></div></body>
//点击打印$('#dy').click(function(){var startStr = "<!--startprint-->";var endStr = "<!--endprint-->";bdhtml=window.document.body.innerHTML;var printHtml = bdhtml.substring(bdhtml.indexOf(startStr) + startStr.length, bdhtml.indexOf(endStr));//将截取的字符串进行打印window.document.body.innerHTML = printHtml;window.print();//打印结束后重新加载页面,否则打印页面点击取消时原页面被修改window.document.body.innerHTML = bdhtml;location.reload();})})
在style中,使用@media print{}
打印时单独用一套样式,就可以方便修改,使用@media print{}不会影响平时展示
@media print{.newWarp{width:380px;height: 100%;margin-left: 100px;}.newWarp .content{width:100%;height: 500px;margin-top: 120px;}.header_{width:100%;height: 430px;background-color: #21AA37;}.logo{height:100px;width:100%;line-height: 100px;color:#ffffff;font-size: 30px;text-align: center;}.img_{width:200px;height: 200px;margin: 0 auto;border:1px solid red;}.footer_d{width:100%;height: 70px;background: url(images/wx.png);background-size: 100% 100%;}}
生成二维码 QRCode
QRCode.js 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成,不依赖任何库
<script src="js/qrcodejs-master/qrcode.js"></script>
//生成二维码var qrcode = new QRCode(document.getElementById("erweima"), {width: 200,height: 200,colorDark : '#000000',colorLight : '#ffffff',correctLevel : QRCode.CorrectLevel.H});$('#qrcode_text').on('change', function() {// 设置参数方式qrcode.makeCode(this.value);setTimeout(function(){var data = $('#erweima img').attr('src');$('#img_ img').attr('src',data)var value_ = $('#qrcode_text').val()console.log(value_);},10)});
