用js在html頁面實現打印功能示例


1.在head標簽內加入一段js

<script language="javascript" type="text/javascript">
        function doPrint() { 
            bdhtml=window.document.body.innerHTML; //獲取當前頁的html代碼
            sprnstr="<!--startprint-->"; //設置打印開始區域
            eprnstr="<!--endprint-->";//設置打印結束區域
            prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);//從開始代碼向后取html
            prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//從結束代碼向前取html
            window.document.body.innerHTML=prnhtml;
            window.print();
        }
    </script>

 

2.需要打印的內容用<!--startprint--><!--endprint-->包起來

<div>
        <!--startprint-->
        <!--打印內容開始-->
        開始和結束標簽內就是需要打印的內容<br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" /><br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" /><br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" /><br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" />
        <!--打印內容結束-->
        <!--endprint-->
    </div>

 

3.加入一個打印按鈕,調用之前的doPrint()方法

<input type="button" id="bt" onclick="javascript:doPrint()"   value="打印" />

通過以上3步連接打印機就可以打印了,需要注意一點,背景圖是不能被打印出來的

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM