js打印隐藏的div,可自定义样式
这里是全部代码,可以直接运行。js需要自行导入
DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>title>
<script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8">script>
head>
<body>
<div id="printcontent" style="display: none;">
<div id="print-div">
<style type="text/css">
.title{
color: red;
}
style>
<div class="title-div">
<span class="title">电子验印结果记录单span>
div>
<table border="0" cellspacing="" cellpadding="">
<tr>
<td>验印时间:2021-03-19 16:39:35td>
<td>账号:91310120MA1HQGCT3Ttd>
tr>
<tr>
<td colspan="2">户名:上海尊煜建筑劳务有限公司td>
tr>
<tr>
<td>凭证金额:2.00td>
<td>出票日期:2021-03-19td>
tr>
table>
div>
div>
<button id="printBtn">打印button>
body>
<script type="text/javascript">
$("#printBtn").click(function() {
doPrint3();
})
function doPrint3(){
//判断iframe是否存在,不存在则创建iframe
var iframe=document.getElementById("print-iframe");
if(!iframe){
var el = document.getElementById("printcontent");
iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute("id", "print-iframe");
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
//这里可以自定义样式
//
doc.write('');
doc.write('' + el.innerHTML + '');
doc.close();
iframe.contentWindow.focus();
}
iframe.contentWindow.print();
document.body.removeChild(iframe);
// if (navigator.userAgent.indexOf("MSIE") > 0){
// document.body.removeChild(iframe);
// }
}
script>
html>