有時候咱們須要使用html+css實現打印A4紙張的功能頁面,如下代碼實現javascript
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>A4打印頁面</title> <style> /*橫向*/ .a4-endwise{ margin: 0 auto; width: 1070px; height: 1550px; border: 1px #ccc solid; overflow: hidden; padding: 0; word-break:break-all; } /*縱向*/ .a4-broadwise{ margin: 0 auto; width: 1569px; height: 1073px; border: 1px #000 solid; overflow: hidden; padding: 0; word-break:break-all; } /*打印按鈕*/ .print{ position: fixed; top: 1%; right: 10%; } </style> </head> <body> <a class="print" href="javascript:;" onclick="preview();">打印</a> <!--startprint--> <div class="container a4-endwise" id="test"> 打印內容-第一頁 </div> <div class="container a4-endwise" id="test2"> 打印內容-第二頁 </div> <!--endprint--> <script> /** * [打印] * @return {[type]} [description] */ function preview(){ //獲取當前頁的html代碼 bdhtml=window.document.body.innerHTML; //設置打印開始區域 sprnstr="<!--startprint-->"; //設置打印結束區域 eprnstr="<!--endprint-->"; //從開始代碼向後取html prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+18); //從結束代碼向前取html prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr)); window.document.body.innerHTML=prnhtml; window.print(); window.document.body.innerHTML=bdhtml; } </script> </body> </html>