Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

javascript - Window.print doesn't work in IE

I have to print out a div which I'm doing in the following way:

function PrintElem(elem)
    {
        Popup(elem.html());
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'to print', 'height=600,width=800');
        mywindow.document.write('<html><head><title></title>');
        mywindow.document.write('<link rel="stylesheet" href="css/mycss.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.print();
        mywindow.close();

        return true;
    }

My problem is that on IE, when I click the button nothing happens. However, on Chrome and Firefox it works. What can I do to print it out correctly?

EDIT: I'm call print in the following way:

$('#print_it').click(function(){
    var element = $('#itinerario');
    PrintElem(element);
});

This is where print_it is the id of the button.

Another thing I've seen is that after a period of time, Chrome along with other browsers tells me that the page isn't responding. Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You MUST do a mywindow.document.close() and you may NOT have a space in the window name

I assume you invoke PrintElem from onclick of something - if that something is a link, you need to return false in the onclick handler!

Here is how I would do it if I had to

function PrintElem(elem) { 
    Popup($(elem).html());
}

function Popup(data) 
{
    var mywindow = window.open('', 'to_print', 'height=600,width=800');
    var html = '<html><head><title></title>'+
               '<link rel="stylesheet" href="css/mycss.css" type="text/css" />'+
               '</head><body onload="window.focus(); window.print(); window.close()">'+
               data+
               '</body></html>';
    mywindow.document.write(html);
    mywindow.document.close();
    return true;
}

but I am not sure whether or not the window.close() will interfere with the printing

And why not

$(function() {
  $('#print_it').click(function(){
    popup($('#itinerario').html());
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...