直接上代码
$.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") + '" >');
});
**/
var _style = '<style type="text/css">'+$("#replay_style").html()+'</style>';
var _html ='<html><head>'+_style+'</head><body ><div style="margin:0px auto;width:600px;">'+$(ele).html()+'</div></body>';
//把不打印的元素去掉
$(".noprint").each(function (i) {
_html=_html.replace($(this).html(), "");
});
doc.write(_html);
doc.close();
var frameWindow = iframe.contentWindow;
frameWindow.close();
frameWindow.focus();
frameWindow.print();
}
var removePrintArea = function (id) {
$("iframe#" + id).remove();
};
这是jq插件里面的一段源代码。我中间注释掉了源代码一段,也修改了一些逻辑。用原代码总是会打印出整个页面。并没有实现局部打印的感觉。。。。也可能是我没用对
调用方式$("#print").printArea();
逻辑:在屏幕可视区域外加一个iframe。把要打印的局部元素放到这个iframe,然后调用js方法print()打印这个iframe。
ps:默认带页眉日期时间标题等等和页脚网页路径。在打印机里面设置一下不要即可。目前本人没有找到js可以修改的方法。