js window.open然后print()

时间:2012-03-24 13:37:39

标签: javascript html printing window

打开新窗口后,

print()在IE中不起作用。它适用于Chrome。 这是一个tester

<html>
<head>
<script type="text/javascript">
  function openWin()
  {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");
    myWindow.focus();
    myWindow.print(); //DOES NOT WORK
  }
</script>
</head>
<body>

<input type="button" value="Open window" onclick="openWin()" />

</body>
</html>

7 个答案:

答案 0 :(得分:25)

答案 1 :(得分:14)

图尔古特给出了正确的解决方案。为了清楚起见,您需要在写完后添加关闭。

function openWin()
  {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");


    myWindow.document.close(); //missing code


    myWindow.focus();
    myWindow.print(); 
  }

答案 2 :(得分:4)

class MyGenericClass<G : GeneratorType> {

    typealias T = G.Element

    var source : G
    var itemsProcessed : [ T ] = []

    // ...
}

答案 3 :(得分:3)

function printCrossword(printContainer) {
    var DocumentContainer = getElement(printContainer);
    var WindowObject = window.open('', "PrintWindow", "width=5,height=5,top=200,left=200,toolbars=no,scrollbars=no,status=no,resizable=no");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

答案 4 :(得分:2)

试试这个

<html>
<head>
<script type="text/javascript">
function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.focus();
print(myWindow);
}
</script>
</head>
<body>

<input type="button" value="Open window" onclick="openWin()" />

</body>
</html>

答案 5 :(得分:1)

对我有用的是在myWindow.document.close()之后添加myWindow.document.write()。这是我的解决方案,超时时要等待新窗口完成加载(如果要加载的内容太多):

var win = window.open('', 'PrintWindow');
win.document.write('Stuff to print...');

setTimeout(function () {
    win.document.close();
    win.focus();
    win.print();
    win.close(); 
}, 1000);

答案 6 :(得分:0)

由于大多数浏览器已更新,因此不再像以前那样打印和关闭。因此,您应该添加 onafterprint 事件监听器,以关闭打印窗口。

    var printWindow = window.open('https://stackoverflow.com/');
    printWindow.print();

    //Close window once print is finished
    printWindow.onafterprint = function(){
       printWindow.close()
    };