<!doctype html>
<html lang='zh-CN'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='ie=edge'>
<title>打印</title>
</head>
<body>
<button onclick='printPage()'>打印</button>
<!--要打印的内容-->
<div id='box'>
<h1>标题</h1>
<table>
<thead>
<th>name</th>
<th>title</th>
<th>level</th>
</thead>
<tbody>
<tr>
<td>海</td>
<td>前端工程师</td>
<td>罢了</td>
</tr>
</tbody>
</table>
</div>
<script>
function printPage() {
var printHTML = document.getElementById('box').innerHTML; // 获取要打印的内容
var page = window.open('', '_blank'); // 打开一个空表窗口,用于打印
page.document.write(printHTML); // 打印页面的内容
page.print(); // 打印
var userAgent = navigator.userAgent;
if ((userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1) || (userAgent.indexOf("Edge") > -1) ||
(userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1)) {
// IE浏览器
page.document.execCommand('print');
} else {
console.log('not IE');
page.document.execCommand('print');
}
}
</script>
</body>
</html>
原文作者:匆匆那年_海,博客主页:https://www.jianshu.com/u/910c0667c515
95后前端汉子,爱编程、优秀、聪明、理性、沉稳、智慧的程序猿一枚。
网友评论