100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > JS打印页面指定区域

JS打印页面指定区域

时间:2022-01-29 20:52:06

相关推荐

JS打印页面指定区域

错误的写法:

//打印function printPage(areaId) {if (parent.$("#PrinFrame").length == 0) {parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');}var prinFrame = parent.$("#PrinFrame")[0];$(prinFrame).contents().find("body").html($("#" + areaId).html());var win = prinFrame.contentWindow;win.document.execCommand('Print');}

View Code

错误原因:只把打印区域的内容放到iframe中,样式信息丢了。

改进后的写法:

//打印function printPage(areaId) {if (parent.$("#PrinFrame").length == 0) {parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');}var prinFrame = parent.$("#PrinFrame")[0];var win = prinFrame.contentWindow;$(prinFrame).attr("src", window.location.href);$(prinFrame).load(function () {$(prinFrame).contents().find("body").html($("#" + areaId).html());win.document.execCommand('Print');});}

View Code

在iframe中重新加载当前页面,然后把body中的内容替换成待打印区域,这样iframe中保留了样式信息。

上面写法的缺点:多次点击打印按钮,iframe的load事件会被绑定多次;打印区域的大小超出A4纸范围;

再次改进后的写法:

//打印function printPage(areaId) {var prinFrame;var win;if (parent.$("#PrinFrame").length == 0) {parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');prinFrame = parent.$("#PrinFrame")[0];win = prinFrame.contentWindow;$(prinFrame).load(function () {setTimeout(function () {var html = '<table style="width:970px;"><tr><td>';html += $("#" + areaId).html();html += '</td></tr></table>';$(prinFrame).contents().find("body").html(html);win.document.execCommand('Print');}, 100);});}else {prinFrame = parent.$("#PrinFrame")[0];}$(prinFrame).attr("src", window.location.href);}

View Code

再次改进后,确保iframe的load事件只被绑定一次;用宽度为970的table限制打印区域大小。

上面的写法还是有错误,重新打开tab页时,点击打印,不再进入iframe的load方法,再修改:

//打印function printPage(areaId) {if (parent.$("#PrinFrame").length == 0) {parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');}parent.$("#PrinFrame").attr("src", window.location.href);parent.$("#PrinFrame").one("load", function () {setTimeout(function () {var html = '<table style="width:970px;"><tr><td>';html += $("#" + areaId).html();html += '</td></tr></table>';parent.$("#PrinFrame").contents().find("body").html(html);parent.$("#PrinFrame")[0].contentWindow.document.execCommand('Print');}, 100);});}

View Code

弄了一天,分页打印的时候还是有问题,如下图:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。