我尝试打印HTML中选择的<div>
标记。我尝试使用以下CSS:
<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" 被打印出来了。在这种情况下该怎么办?