代码也是在网络上找到的,现记录下来
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);
页面上调用
如果需要打印下面的div
1 <div class="imgCnt"> 2 ………… 3 </div>
页面js部分中加入下面代码就可以了
$(".imgCnt").printArea();