window.close()的;在window.print()之后; JavaScript的

时间:2014-01-28 13:13:34

标签: javascript

我需要一个js代码,它会在出现弹出打印窗口后立即关闭窗口。这是我的代码:

<a href="javascript:;" onclick="print()">Print</a>

function print()
{   
    win = window.open();
    win.document.write('<html><head>blablabla.......');
    win.window.print();
    win.window.close();
}

但它不起作用,因为窗口在弹出之前关闭。

5 个答案:

答案 0 :(得分:2)

这样,打印后窗口就会关闭,效果很好!

function printme() {         
     var newWindow = window.open();
     newWindow.document.open("text/html");
     newWindow.document.write('<html><head>blablabla.......');
     newWindow.document.close();

     newWindow.print();
     newWindow.onfocus = function () {
        newWindow.close(); // Close the window
     }
};

答案 1 :(得分:2)

此代码对我有用:

print = function() {
    var printContents = document.getElementById('div').innerHTML,
      params = [
        'height=' + screen.height,
        'width=' + screen.width,
        'fullscreen=yes'].join(','),

    popup = window.open("", 'popUpWindow', params);
    popup.document.write('<html><head><link rel="stylesheet" type="text/css" href="/style.css" /></head><body class="print" onload="window.print()" onmousemove="setTimeout(function () {window.close()},1000);" >'
      + printContents
      + '</body></html>');
    popup.onfocus = function () {
      setTimeout(function () {
        popup.focus();
        popup.document.close();
      }, 200);
    };
};

答案 2 :(得分:1)

<a href="javascript:;" onclick="print()">Print</a>

    function print()
    {   
        win = window.open();
        win.document.write('<html><head>blablabla.......');

        var document_focus = false; // var we use to monitor document focused status.
        // Now our event handlers.
        $(document).ready(function() { win.window.print();document_focus = true; });
        setInterval(function() { if (document_focus === true) { win.window.close(); }  }, 300);
    }

感谢Stilltorik link

答案 3 :(得分:0)

JQuery中的此片段还会打印在html中呈现的动态图像。

  <button id="printreceipt">
  Print
  </button>
  <div id="receipt">
  Colombo was great..
  </div>

$(function(){
$('body').on('click','button#printreceipt',function(e){
e.preventDefault();
e.stopPropagation();

var printWindow = window.open('');
var divContents = $("#receipt").html() +
                    "<script>" +
                    "window.onload = function() {" +
                    "     window.print();" +
                    "};" +
                   "setInterval(function() {   {   clearInterval();window.close(); }  }, 300);" +
                    "<" + "/script>";
 printWindow.document.write(divContents);
 printWindow.document.close();
 });
});

答案 4 :(得分:0)

这对我有用(在Chrome上):

var html = "<html>...</html>";
var win = window.open();
win.document.write(html);
win.document.close();
setTimeout(function () {
   win.focus();
   win.print();
   win.close();
}, 100);

关键是做焦点()和print()异步。没有它,我在打印预览中看到一个空白页面。