標籤:href content document ack .com code doctype device tco
基於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: iframeId14 });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局部列印外掛程式使用