要快速而准确地请see this fiddle。首次点击标签为" print"的按钮,将打开一个新窗口(打印内容),然后打印一个对话框将弹出并且应该有内容,因为我已经设置了它的内容但是没有显示内容,但是有打印对话框的标题。现在,如果您再次点击(第二次点击)标签为" print"的按钮,现在会显示打印对话框的内容,有关进展情况的任何想法或线索?帮助,建议,建议让它总是显示?
这是我的原始代码
<button>Print</button>
<div id="print">
<table>
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jason Guatamala</td>
<td>Male</td>
<td>18</td>
<td>Somewhere</td>
</tr>
</tbody>
</table>
</div>
jquery
$(document).ready(function(){
$("button").click(function(){
$("#print").print();
});
});
(function ( $ ) {
$.fn.print = function(){
var content = $(this).html();
var style = '<style media="print" type="text/css">body{font-family: Roboto, sans-serif;font-weight:500;font-size:13px;-webkit-print-color-adjust: exact;}table{width:100%;font-size:12px!important;}table tr td{border:1px solid rgba(0,0,0,.05);padding:3px;}table tr:nth-of-type(4n+1),table tr:nth-of-type(4n+2),table tr:nth-of-type(4n+3),table tr:nth-of-type(4n+4){background:#eee}table tr:nth-of-type(8n),table tr:nth-of-type(8n-1),table tr:nth-of-type(8n-2),table tr:nth-of-type(8n-3){background:#ddd}</style>';
var w = window.open('TT COLLECTION','', '');
w.document.write('<html><head><title>TT COLLECTION</title><link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">' + style + '</head><body><div style="font-size: 13px !important;" id="lf_print_main_wrapper">' + content + '</div></body></html>');
w.print();
w.close();
};
}( jQuery ));
答案 0 :(得分:1)
因为document.write
无法立即更新DOM&amp;在新打开的窗口中被阻挡。将立即调用下一条指令w.print();
。
因此,您可以稍后通过print
setTimeout
方法
setTimeout(function(){w.print();w.close();}, 2000);
答案 1 :(得分:1)
问题是在调用w.print()
函数之前,新窗口的DOM还没有完成渲染。一种方法是将print函数添加到新窗口HTML底部的脚本标记中,以便在DOM完成渲染后执行...
/* ... other code ... */ content + '</div><scr'+'ipt>window.print();</scr'+'ipt></body></html>');
// don't need w.print here anymore
w.close();