[英]Open print dialog window with different HTML content
在玩耍(和一些谷歌搜索)之后,我提出了這個解決方案:
我向當前視圖添加了一個non-printable
printable
類,向可打印的容器元素添加了一個non-printable
類。 在我的 CSS 中,我使用了css 媒體查詢,其中@media screen
和@media print
狀態包含相應的顯示行為:
@media screen {
.printable { display: none; }
.non-printable { display: block; }
}
@media print {
.printable { display: block; }
.non-printable { display: none; }
}
現在,我可以從當前視圖打印新內容,而無需打開新選項卡或更改當前視圖。
我不確定這是否真的是您問題的答案,因為您的問題幾乎沒有關於打開新窗口的含義的詳細信息。
如果你在 /page/one 並且你想打開一個鏈接 /report/page 並自動打開打印對話框......那么這就像在加載事件上觸發window.print
一樣簡單,例如
<body onload='window.print()'>
如果您不希望該頁面始終打開打印對話框,則在您想要打印時以及在 URL 中找到該頁面時,創建指向新頁面的鏈接/report/page?print=1
或其他類似內容觸發 onload 事件。
在 div 中包含可打印的內容。 喜歡:
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p>
查詢:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
它只會打印可打印的 div。謝謝
有一個很好的 Javascript 插件叫做PrintThis可以很容易地完成這個。
您只需要使用jQuery
選擇器並調用插件,例如:
$('selector').printThis();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.