window.print() 在 Internet Explorer 中挂起

window.print() hangs in internet explorer

我正在尝试打开 new window 和 print 的内容。

var parentHeader= $("head").html();
var parentDivContent = $("#printer_data_1").html();
var newW= window.open("", "", "scrollbars=1,width=200,height=200");
    newW.document.write('<html><head><title>Title</title>'+parentHeader+'</head>');
    newW.document.write('<body><div>');
    newW.document.write(parentDivContent );
    newW.document.write('</div></body></html>');
    newW.document.close();
    newW.print();
    newW.close();

当我尝试 运行 上面的 code 时,它挂在 IE8 中,当我评论下面的行时...它有效。

newW.document.write('<html><head><title>Title</title>'+parentHeader+'</head>');

我想要在新 window.

的头部部分加载全部内容和样式

want the entire content, styles to be loaded in the head section of new window

尝试将 html for newW 编译成单个字符串,包括 head html parentHeader ;在调用 window.open() 的第二个参数中为 newW 设置 name 引用;使用单个 html 字符串作为参数调用 document.write

var parentHeader= $("head").html();
var parentDivContent = $("#printer_data_1").html();
var newW= window.open("", "newW", "scrollbars=1,width=200,height=200");
var html = "<html>" 
           + parentHeader // `parentHeader` `head` `html`
           + "<body><div>" 
           + parentDivContent 
           + "</div></body></html>"
newW.document.write(html);
newW.document.close();
newW.print();
newW.close();

您可能想使用 innerHTML 而不是 document.write。那可能是你的问题。

var someVar = 50,
  el = document.getElementById('btn');

function onOpen() {
  var prnt = open();
  prnt.document.title = 'Page Title';
  prnt.document.body.innerHTML = [
    '<h1>',
    'heading of the page',
    someVar,
    '</h1>',
    '<p>A paragraph with text.</p>'
  ].join('');
  prnt.print();
  prnt.close();
}

el.attachEvent('onclick', onOpen);
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Print for Legacy IE</title>
</head>

<body>

  <a id="btn" href="#">Link</a>

</body>

</html>