首页 > 代码库 > jquery局部打印插件使用

jquery局部打印插件使用

基于jquery库的jquery.PrintArea.js插件源代码为:

 1 (function ($) {
 2     var printAreaCount = 0;
 3     $.fn.printArea = function () {
 4         var ele = $(this);
 5         var idPrefix = "printArea_";
 6         removePrintArea(idPrefix + printAreaCount);
 7         printAreaCount++;
 8         var iframeId = idPrefix + printAreaCount;
 9         var iframeStyle = ‘position:absolute;width:0px;height:0px;left:-500px;top:-500px;‘;
10         iframe = document.createElement(‘IFRAME‘);
11         $(iframe).attr({
12             style: iframeStyle,
13             id: iframeId
14         });
15         document.body.appendChild(iframe);
16         var doc = iframe.contentWindow.document;
17         $(document).find("link").filter(function () {
18             return $(this).attr("rel").toLowerCase() == "stylesheet";
19         }).each(
20                 function () {
21                     doc.write(‘<link type="text/css" rel="stylesheet" href="‘
22                             + $(this).attr("href") + ‘" >‘);
23                 });
24         doc.write(‘<div class="‘ + $(ele).attr("class") + ‘">‘ + $(ele).html()
25                 + ‘</div>‘);
26         doc.close();
27         var frameWindow = iframe.contentWindow;
28         frameWindow.close();
29         frameWindow.focus();
30         frameWindow.print();
31     }
32     var removePrintArea = function (id) {
33         $("iframe#" + id).remove();
34     };
35 })(jQuery);

插件使用方法:

 1 <!DOCTYPE html>
 2 <html lang="zh">
 3 
 4     <head>
 5         <meta charset="UTF-8" />
 6         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 7         <meta http-equiv="X-UA-Compatible" content="ie=edge" />
 8         <title>jquery.PrintArea.js 插件使用</title>
 9     </head>
10 
11     <body>
12         <div>
13             <button id="print">打印</button>
14         </div>
15         <div id="printContent">
16             局部打印
17         </div>
18         <!--需要引入jquery库-->
19         <script src="../jquery/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
20         <script src="jquery.PrintArea.js" type="text/javascript" charset="utf-8"></script>
21         <script type="text/javascript">
22             $(#print).click(function() {
23                 $("#printContent").printArea();
24             });
25         </script>
26     </body>
27 
28 </html>

效果:

技术分享

 

jquery局部打印插件使用