<input type=”button” class=”btn btn-primary” value=”立即打印” onclick=”printpage()” />

<div id=”print-layout”>

需要打印的内容

</div>

<script>
function printpage(){
//判断iframe是否存在,不存在则创建iframe
var iframe=document.getElementById(“print-iframe”);
if(!iframe){
var el = document.getElementById(“print-layout”);
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(`
<html>
<head>
<style>
table {
border-collapse: collapse!important;
border: 1pt solid #000!important;
}

th, td {
border: 1pt solid #000!important;
}
</style>
</head>
<body>
<div>${el.innerHTML}</div>
</body>
</html>
`);
doc.close();
iframe.contentWindow.focus();
}
setTimeout(function(){ iframe.contentWindow.print();},50) //解决第一次样式不生效的问题
if (navigator.userAgent.indexOf(“MSIE”) > 0){
document.body.removeChild(iframe);
}
}
</script>

作者 admin

百度广告效果展示