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




JS实现局部打印和预览:
第一种:

function preview(oper)
{
    bdhtml=window.document.body.innerHTML;//获取当前页的html代码
    sprnstr="<!--startprint-->";//设置打印开始区域自己设定的一个开始表示符
    eprnstr="<!--endprint-->";//设置打印结束区域自己设定的一个结束符
    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;
}


使用很简单 将页面内要打印的内容加入中间<!--startprint-->XXXXX<!--endprint--> 再加个打印按纽 onclick=preview()
第二种
 
function Printpart(id_str)//id-str 内容中的id{
    var el = document.getElementById(id_str);//获取要打印的最外层元素
    var iframe = document.createElement('IFRAME');//创建一个Iframe包含该打印内容
    var doc = null;
    iframe.setAttribute('style', 'position:absolute;width: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 当参数放入函数就可以了。

打赏

取消 我去学网

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少
微信

打开微信扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

  1. #2

    木庄网络博客(2016/10/28 11:41:03)
    不错的网站主题,看着相当舒服

  2. #1

    木庄网络博客(2016/10/14 21:02:39)
    博客做得好漂亮哦!