原文链接:https://segmentfault.com/a/1190000006236133
利用iframe存放打印的内容,但是要注意把样式也放进iframe中,不然iframe中是没有样式的。.
代码如下:
<!DOCTYPE html> <html lang="en" data-theme="skin0"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="renderer" content="webkit"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1, user-scalable=no"> <title>条形码</title> <link rel="stylesheet" type="text/css" href="./css/txm.css" /> </head> <body> <button type="button" class="printbtn" onclick="doPrint()">打印预览</button> <!--startprint--> <div class="container-fluid" id="test"> <div class="row"> <div class="txmrow"> <div class="txm"> <div class="txmimg"><img src="./img/txm.png" alt=""></div> <div class="txmtext"><span>姓名:李昌盛</span><span>性别:男</span><span>班级:七年级1班</span></div> <div class="txmtext"><span>学校:贵阳市第二中学</span></div> </div> <div class="txm"> <div class="txmimg"><img src="./img/txm.png" alt=""></div> <div class="txmtext"><span>姓名:李昌盛</span><span>性别:男</span><span>班级:七年级1班</span></div> <div class="txmtext"><span>学校:贵阳市第二中学</span></div> </div> </div> <div class="txmrow"> <div class="txm"> <div class="txmimg"><img src="./img/txm.png" alt=""></div> <div class="txmtext"><span>姓名:李昌盛</span><span>性别:男</span><span>班级:七年级1班</span></div> <div class="txmtext"><span>学校:贵阳市第二中学</span></div> </div> <div class="txm"> <div class="txmimg"><img src="./img/txm.png" alt=""></div> <div class="txmtext"><span>姓名:李昌盛</span><span>性别:男</span><span>班级:七年级1班</span></div> <div class="txmtext"><span>学校:贵阳市第二中学</span></div> </div> </div> </div> </div> <!--endprint--> <iframe id="printf" src="" width="0" height="0" frameborder="0"></iframe> </body> <script src="./js/jquery-1.11.1.min.js"></script> <script> function doPrint() { //获取当前页的html代码 var bodyhtml = window.document.body.innerHTML; //设置打印开始区域、结束区域 var startFlag = "<!--startprint-->"; var endFlag = "<!--endprint-->"; // 要打印的部分 var printhtml = '<link rel="stylesheet" type="text/css" href="./css/txm.css" />' + bodyhtml.substring(bodyhtml.indexOf(startFlag), bodyhtml.indexOf(endFlag)); console.log(printhtml); // 生成并打印ifrme var f = document.getElementById('printf'); f.contentDocument.write(printhtml); f.contentDocument.close(); f.contentWindow.print(); } </script> </html>