我試圖在HTML中打印選定的<div>
標籤。我嘗試使用這樣的CSS:如何打印HTML頁面的選定部分?
<style media="print">
.onlyscreen {
display: none;
}
</style>
<html>
<body>
<div class="onlyscreen">
<p>Hello</p>
<div>
<p> Inner tag</p>
</div>
</div>
<input type="submit" value="Print Report" onclick="window.print()">
</body>
</html>
「內部標記」未打印。這是一種有用的技術,但在分層<div>
標籤時失敗。
我也試過這個JavaScript:
function printContent(id) {
str = document.getElementById(id).innerHTML;
newwin = window.open('', 'printwin', 'left=100,top=100,width=400,height=400');
newwin.document.write('<HTML>\n<HEAD>\n');
newwin.document.write('<TITLE>Report</TITLE>\n');
newwin.document.write('<script>\n');
newwin.document.write('function chkstate(){\n');
newwin.document.write('if(document.readyState=="complete"){\n');
newwin.document.write('window.close()\n');
newwin.document.write('}\n');
newwin.document.write('else{\n');
newwin.document.write('setTimeout("chkstate()",2000)\n');
newwin.document.write('}\n');
newwin.document.write('}\n');
newwin.document.write('function print_win(){\n');
newwin.document.write('window.print();\n');
newwin.document.write('chkstate();\n');
newwin.document.write('}\n');
newwin.document.write('<\/script>\n');
newwin.document.write('</HEAD>\n');
newwin.document.write('<BODY onload="print_win()">\n');
newwin.document.write(str);
newwin.document.write('</BODY>\n');
newwin.document.write('</HTML>\n');
newwin.document.close();
}
然後通過onclick
調用這個函數。這個腳本可以很好地處理一個<div>
標記,但不能使用多個標記。例如
<html>
<body>
<div id="print_thistag">
<p>Hello</p>
</div>
<div id="print_thistag">
<p>User</p>
</div>
<input type="submit" value="Print Report" onclick="printContent('print_thistag')">
</body>
</html>
只打印「Hello」。在這種情況下我應該怎麼做?
@BalusC - 感謝BalusC正確描繪我的問題:) – Dhruv