簡單的瀏覽器列印demo(相容chrome/IE/firefox,表現略有差異)
阿新 • • 發佈:2019-01-08
目前在chrome/IE11/firefox下都能執行,但效果略有差異,只有chrome有預覽功能。
chrome效果:
firefox效果:
IE效果圖:
程式碼:
<!doctype html>
<html lang='en'>
<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>
<style>
#printPage {
display: none;
}
</style>
</head>
<body>
哈哈哈,拜託印表機了
<button onclick='printPage()'>戳我列印</button>
<!--實際要列印的內容放在這個div中-->
<div id='printPage'>
<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('printPage').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.close();// 關閉列印視窗
}
</script>
</body>
</html>