<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function do_print(id_str){
//id-str 打印区域的id
var el = document.getElementById(id_str);
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style','position:absolute;0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的专有CSS样式,根据实际修改
//doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0){
document.body.removeChild(iframe);
}
}
</script>
</head>
<body>
<!--打印区域: -->
<div id="print_box">
<div style=" 500px; height: 500px; border: 5px solid #6b3906;">
<h1>hello kitty!</h1>
</div>
</div>
<!--// 调用打印 -->
<button onclick="javascript:do_print('print_box');">打印</button>
</body>
</html>
实战项目中的使用
$scope.do_print = function (id_str) {
//id-str 打印区域的id
var el = document.getElementById(id_str);
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style', 'position:absolute;0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的专有CSS样式,根据实际修改
//doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");
if ($scope.orderinfo.inv==null) {
var txt = "table{border-collapse:collapse;border-spacing:0;border-left:1px solid #000000;border-top:1px solid #000000;} td{border: 1px solid #000000;}th{border: 1px solid #000000;}#changefapiao{visibility: hidden;} .change{border-right: 0px solid #000000;}.change1{border-left: 0px solid #000000;} .title{text-align:center;} #fapiao{display:none;}";
}
else {
var txt = "table{border-collapse:collapse;border-spacing:0;border-left:1px solid #000000;border-top:1px solid #000000;} td{border: 1px solid #000000;}th{border: 1px solid #000000;}#changefapiao{visibility: hidden;} .change{border-right: 0px solid #000000;}.change1{border-left: 0px solid #000000;} .title{text-align:center;}";
}
doc.write('<style>' + txt + '</style>');
doc.write('<body>' + el.innerHTML + '</body>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0) {
document.body.removeChild(iframe);
}
}