第一种:
<!--startprint1-->
……打印的内容放在这里……
<!--endprint1-->
//打印 function preview(DivID) { if (oper < 10) { bdhtml = window.document.body.innerHTML; //获取当前页的html代码 sprnstr = "<!--startprint" + oper + "-->"; //设置打印开始区域 eprnstr = "<!--endprint" + oper + "-->"; //设置打印结束区域 prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + 18); //从开始代码向后取html prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr)); //从结束代码向前取html window.document.body.innerHTML = prnhtml; window.print(); window.document.body.innerHTML = bdhtml; } else { window.print(); } }
<input type="button" value="打印" id="btnPrint" onclick="preview('ex')" />
第二种
//打印 function preview(DivID) { var disp_setting = "toolbar=yes,location=no,"; disp_setting += "directories=yes,menubar=yes,"; disp_setting += "scrollbars=yes,width=985px"; var content_vlue = document.getElementById(DivID).innerHTML; var docprint = window.open("", "", disp_setting); docprint.document.open(); docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'); docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'); docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'); docprint.document.write('<head><title>My Title</title>'); docprint.document.write('<style type="text/css"> table.gridtable{font-family: verdana,arial,sans-serif;font-size: 14px;color: #123456; border-width: 1px;border-color: #123456;border-collapse: collapse; width: 985px;}'); docprint.document.write('table.gridtable th{border: 1px solid #666666;padding: 8px;background-color: #dedede;text-align: center;}'); docprint.document.write('table.gridtable td{border: 1px solid #666666;padding: 8px;color: #123455;font-size: 13px;height: 10px;background-color: #ffffff;text-align: center;}'); docprint.document.write('table.gridtable th{border: 1px solid #666666;padding: 8px;background-color: #dedede;text-align: center;}'); docprint.document.write('#JXFX div h1{background-color: #D1D1D1;width: 35%;letter-spacing: 2.5px;}'); docprint.document.write('#JXFX #getMonthWeek{width: 130px;text-align: center;float: right;}'); docprint.document.write('</style>'); docprint.document.write('</head><body onLoad="self.print()"><center>'); docprint.document.write(content_vlue); docprint.document.write('</center></body></html>'); docprint.document.close(); docprint.focus(); }
这个可以自己设置样式,直接拼接起你想要的样式就可以了
<input type="button" value="打印" id="btnPrint" onclick="preview('ex')" />