标签:doctype color cal style tab pre var utf-8 iframe
先创造一个ifarme元素
然后把要打印额内容插入到ifarme中
最重要是页面加载完成时触发print方法
话不多说上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>打印练习</title>
</head>
<body>
<script src="./jQuery-2.2.0.min.js"></script>
<div>
<input type="text" id="input">
<button id="btn">打印</button>
</div>
<script>
var btn = document.getElementById("btn")
btn.onclick = function(){
var iframe = document.createElement("iframe");
$(iframe).css({width: 0, height: 0});
document.body.appendChild(iframe);
iframe.contentWindow.document.write(`
<!DOCTYPE html>
<html><head><title></title><style >
/* @media print { @page { size:A4; table:{ width:100%, height:100%}}} */
body, div, h3 {
width: 840px;
height: 560px;
border: 0;
margin: 0;
padding: 0
}
</style></head>
<body onload=" print();">
<div style="background-color: aqua;">
<h3 style="color:red">打印练习</h3>
<p>第一行数据</p>
<p>第二行数据</p>
<p>第三行数据</p>
<p>第四行数据</p>
</div>
</body></html>
`)
iframe.contentWindow.document.close()
}
</script>
</body>
</html>
标签:doctype color cal style tab pre var utf-8 iframe
原文地址:https://www.cnblogs.com/cwl1025/p/14817920.html