Window.Print()无法在chrome / Firefox中使用

时间:2012-11-08 09:00:26

标签: javascript dom

我使用以下代码在div中打印内容。它在IE中很好看,但它在chrome和firefox中显示空白。

代码:

var DocumentContainer = document.getElementById('TermsMainDiv');
    var WindowObject = window.open('', "PrintWindow", 
"width=800,height=700,top=200,left=200,toolbars=no,scrollbars=yes,status=no,resizable=no");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();

2 个答案:

答案 0 :(得分:1)

IE和其他浏览器的单独代码。现在工作正常。

代码:

 <script type='text/javascript'>
 var originalContents;
    function Print() {

        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            var DocumentContainer = document.getElementById('TermsSCMainDiv');
            var WindowObject = window.open('', "PrintWindow", 
"width=800,height=700,top=200,left=200,toolbars=no,
 scrollbars=yes,status=no,resizable=no");
            WindowObject.document.writeln(DocumentContainer.innerHTML);
            WindowObject.document.close();
            WindowObject.focus();
            WindowObject.print();
            WindowObject.close();
        }
        else {
            originalContents = document.body.innerHTML;
            var printable = document.getElementById('TermsSCMainDiv');
            document.body.innerHTML = printable.innerHTML;
            printCoupon();
        }
    }

    function printCoupon() {
        window.print();
        endPrintCoupon();
    }

    function endPrintCoupon() {
        document.body.innerHTML = originalContents;
        document.getElementById('TermsSCMainDiv').scrollIntoView(true);
        location.reload();
    }
 </script>

答案 1 :(得分:0)

这似乎也有效:

WindowObject.document.writeln(html);
WindowObject.document.close();
WindowObject.scrollTo(0,0); 
WindowObject.focus();
WindowObject.print();

当我发现注释掉.print()函数导致弹出页面的正确呈现时,发现了这一点。 scrollTo触发通常由页面前面的打印对话框阻止的渲染。