JS 实现简单的页面局部打印

JS实现局部打印和预览:
第一种:
JS 实现简单的页面局部打印

function preview(oper)
{
if (oper < 10)...{
bdhtml=window.document.body.innerHTML;//获取当前页的html代码
sprnstr="<!--startprint"+oper+"-->";//设置打印开始区域
eprnstr="<!--endprint"+oper+"-->";//设置打印结束区域
prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+18); //从开始代码向后取html

prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html
window.document.body.innerHTML=prnhtml;
window.print();
window.document.body.innerHTML=bdhtml;


} else {
window.print();
}

}

使用很简单 将页面内要打印的内容加入中间<!--startprint1-->XXXXX<!--endprint1-->
再加个打印按纽 onclick=preview(1)

第二中:
下面就是实现局部打印的代码,跟大家分享一下,希望能够对大家有所帮助。

function Printpart(id_str)//id-str 内容中的id
{
var el = document.getElementById(id_str);
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style', 'position:absolute;0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0)
{
document.body.removeChild(iframe);
}
}

将要想打印局部内容,将包含内容的标签ID 当参数放入函数就可以了。

如果这篇文章对您有帮助,您可以打赏我

技术交流QQ群:15129679

原文地址:https://www.cnblogs.com/yeminglong/p/2799957.html