使用window.print()時會出現兩個問題:css
(1)直接使用window.print() 打印的是整頁內容-->沒法實現打印指定區域html
(2)打印時替換body中的內容,打印完成後再替換回來-->這樣會致使原來頁面狀態失效spa
使用iframe便可打印指定內容,也可保證頁面不失效,具體方法以下:code
一、將打印的內容獨立出來爲一個print.html文件,併爲頁面添加打印事件htm
<!DOCTYPE html> <html> <head> ... </head> <body> ...打印內容 </body> <script> function iframePrint(){ //添加打印事件 window.print(); } </script>
二、在原頁面中使用iframe引入打印頁面blog
<!DOCTYPE html> ... <iframe src="print.html" frameborder="0" id="printIframe" name="printIframe" ></iframe> ... <button id="btn">打印</button> ...
三、打印事件綁定,在原頁面中調用print.html中的打印事件(爲方便表示這裏使用jq綁定事件)事件
$("#btn").on("click",function(){ document.getElementById('printIframe').contentWindow.iframePrint(); })
至此,點擊打印便可實現iframe中內容的打印 ;ip
///////////////////////////方式二////////////////////////////////////get
固然,還有一種方式就是使用媒體查詢寫兩套樣式也可實現iframe
<style type="text/css"> h1 {color:#FF0000;} ...網頁顯示css </style> <style type="text/css" media="print"> h1 {color:#000000;} ...打印css </style>