【JS】調用瀏覽器打印功能


參考文獻:https://blog.csdn.net/qq_32540639/article/details/74909891

 

<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>局部打印案例</title>  
<script type="text/javascript">     
    function doPrint() {      
        //取得瀏覽器的userAgent字符串
        bvar userAgent = navigator.userAgent.toLowerCase(); 
        if (userAgent.indexOf("trident") > -1 || userAgent.indexOf('msie') > -1) {
            alert("請使用google或者360瀏覽器打印");
            return false;
        } 

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

<body>  
<p>1不需要打印的地方</p>  
<p>2這里不要打印啊</p>  
<!--startprint--><!--注意要加上html里star和end的這兩個標記-->  
<div class="m-page" contenteditable="true">
<h1>打印標題</h1>  
<p>打印內容</p>  
</div>
<!--endprint-->  
<button type="button" onclick="doPrint()">打印</button>  
<p>不打印的地方啊哈哈哈哈</p>  
<p>2</p>  
</body>  
</html> 

  

【注意】contenteditable屬性,將頁面需要打印部分的功能可以點擊編輯,再打印  

 


免責聲明!

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



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