2016-03-07 55 views
0

要快速和精確請撥打see this fiddle。首先點擊具有「打印」標籤的按鈕,打開一個新窗口(打印內容),然後一個打印對話框將會彈出,並且應該有內容,因爲我已經設置了它的內容,但是沒有顯示內容,但是有打印對話框的標題。現在,如果再次點擊(第二次點擊)標籤爲「打印」的按鈕,現在正在顯示打印對話框的內容,有關正在進行的任何想法或線索?幫助,建議,使其始終顯示的建議?自定義打印功能,在第一個事件觸發器上沒有顯示打印內容

這裏是我的原始代碼

<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)); 

回答

1

了一下後調用print方法的問題是,在新窗口中的DOM還沒有完成渲染稱爲w.print()函數之前。一種方法是將打印功能在新窗口中的HTML的底部添加到腳本標籤,從而使DOM呈現完畢後,執行...

/* ... other code ... */ content + '</div><scr'+'ipt>window.print();</scr'+'ipt></body></html>'); 
    // don't need w.print here anymore 
    w.close(); 

小提琴:https://jsfiddle.net/b0qfsyxb/6/

+0

很酷,但有沒有辦法在關閉打印對話框後關閉打開的窗口? –

1

因爲document.write不能在新打開的窗口更新DOM立即&阻擋地。下一條指令w.print();將立即被調用。

所以,你可以通過setTimeout

setTimeout(function(){w.print();w.close();}, 2000); 
+0

但問題是由於服務器或網絡負載性能而導致內容在新的打開窗口上顯示時間過長,然後在設置超時(2000)後觸發腳本,然後內容仍然不會在打印對話框中顯示時出現實例。 –