兼容IE8的打印页面局部区域

/**
 * 兼容IE8的打印页面局部区域
 * $('#printBody')为页面上0宽0高的div
 * @param printhtml 要打印的区域的innerHTML
 */
function printOrder(printhtml) {
    //清空之前打印插入的html
    $('#printBody').html('');
    //新建一个iframe
    var iframe = document.createElement('iframe');
    iframe.id = 'printf';
    //iframe宽高设置,因为IE8下iframe不能设为0宽,这里写1
    iframe.style.width = '1';
    iframe.style.height = '1';
    iframe.style.border = "none";
    //将iframe插入到printBody里
    document.getElementById("printBody").appendChild(iframe);
    setTimeout(function () {
        if (document.all) {
            //IE下,在iframe里调用打印
            iframe.contentDocument.write("<script type='text/javascript'> window.onload=function(){ document.execCommand('print'); } </script>" + printhtml);
            iframe.contentDocument.close();
        } else {
            //其它浏览器直接调用
            iframe.contentDocument.write(printhtml);
            iframe.contentDocument.close();
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
        }
    }, 100)
};

 

posted @ 2020-10-16 09:21  AAA_boy  阅读(222)  评论(0编辑  收藏  举报