js代码:
// JavaScript Document
(function($) {
var printAreaCount = 0;
$.fn.printArea = function()
{
var ele = $(this);
var idPrefix = "printArea_";
removePrintArea( idPrefix + printAreaCount );
printAreaCount++;
var iframeId = idPrefix + printAreaCount;
var iframeStyle = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;';
iframe = document.createElement('IFRAME');
$(iframe).attr({
style : iframeStyle,
id : iframeId
});
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
$(document).find("link").filter(function(){
return $(this).attr("rel").toLowerCase() == "stylesheet";
}).each(function(){
doc.write('<link type="text/css" rel="stylesheet" href="' +$(this).attr("href") + '" >');
});
doc.write('<div class="' + $(ele).attr("class") + '">' + $(ele).html() + '</div>');
doc.close();
var frameWindow = iframe.contentWindow;
console.log(frameWindow);
frameWindow.close();
frameWindow.focus();
frameWindow.print();
}
var removePrintArea = function(id)
{
$( "iframe#" + id ).remove();
};
})(jQuery);
实列:
<input type="button" id="btnPrint" value="打印"/>
<div id="printContent">要打印的内容区域<div>
<script type="text/javascript">
$(function(){
$("btnPrint").click(function(){ $("printContent").printArea(); });
});
</script>
本文介绍了一款基于jQuery的JavaScript插件,该插件能够帮助开发者轻松实现网页局部区域的打印功能。通过创建一个隐藏的iframe,并将指定的DOM元素复制到其中进行打印,有效避免了整个页面内容一同被打印的问题。
1493

被折叠的 条评论
为什么被折叠?



