错误的写法:
//打印function printPage(areaId) { if (parent.$("#PrinFrame").length == 0) { parent.$("body").append('<iframe id="PrinFrame" ></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" ></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中保留了样式信息。
原标题:JS打印页面指定区域
关键词:JS