window.print()打印頁面指定內容(使用iframe保證原頁面不失效)


使用window.print()時會出現兩個問題:

(1)直接使用window.print() 打印的是整頁內容-->無法實現打印指定區域

(2)打印時替換body中的內容,打印完成后再替換回來-->這樣會導致原來頁面狀態失效

 使用iframe即可打印指定內容,也可保證頁面不失效,具體方法如下:

1、將打印的內容獨立出來為一個print.html文件,並為頁面添加打印事件

<!DOCTYPE html>
<html>
<head>
   ...
</head>
<body>
    ...打印內容
</body>
<script>
    function iframePrint(){    //添加打印事件
      window.print();
    }
</script>

2、在原頁面中使用iframe引入打印頁面

<!DOCTYPE html>
...
<iframe src="print.html" frameborder="0" id="printIframe" name="printIframe" ></iframe>
...
<button id="btn">打印</button>
...

3、打印事件綁定,在原頁面中調用print.html中的打印事件(為方便表示這里使用jq綁定事件)

$("#btn").on("click",function(){
        document.getElementById('printIframe').contentWindow.iframePrint();
})

 

至此,點擊打印即可實現iframe中內容的打印 ;

 

///////////////////////////方式二////////////////////////////////////

當然,還有一種方式就是使用媒體查詢寫兩套樣式也可實現

<style type="text/css">
    h1 {color:#FF0000;}
    ...網頁顯示css
</style>

<style type="text/css" media="print">
    h1 {color:#000000;}
    ...打印css
</style>

 


免責聲明!

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



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