使用javascript打印页面无效

Printing a page using javascript does not work

本文关键字:无效 打印 javascript 使用      更新时间:2023-09-26

以下HTML页面应该打开http://www.seznam.cz在新窗口中,然后打开"打印"对话框以允许打印。

<html>
    <head>
        <script>
            function printPage() 
            {
                var newWindow = window.open("http://www.seznam.cz", "seznam");
                newWindow.document.close();
                newWindow.focus();
                newWindow.print();
                newWindow.close();
            }
        </script>
    </head>
    <body>
        <a onClick="printPage(); return false;" href="">Print</a>
    </body>
</html>

但是,它只打印一个空白页,右上角有"about:black",右下角有当前日期和时间。

为什么它不能按预期工作?

试试这个。。它将打印页面。您可以将其更改为"您的要求"。

<input type="button" value="Print" onclick="printPage('content');"></input>
function printPage(id)
{
   var html="<html>";
   html+= document.getElementById(id).innerHTML;
   html+="</html>";
   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();

}

原因是,因为您在函数中再次关闭了窗口。删除

newWindow.document.close();
newWindow.close();

出现空白页的原因是,因为您已将空字符串指定为href值。从标记中删除href属性。