JavaScript打印頁面指定div區域原理:使用window.open()在瀏覽器打開一個新的頁面(window), 使用 window.document.write()將指定div區域的內容寫入新窗口文檔,document.close()關閉文檔,使用window.print()調用打印機打印當前文檔。
JavaScript打印函數myPrint(obj):
function myPrint(obj){
//打開一個新窗口newWindow
var newWindow=window.open("打印窗口","_blank");
//要打印的div的內容
var docStr = obj.innerHTML;
//打印內容寫入newWindow文檔
newWindow.document.write(docStr);
//關閉文檔
newWindow.document.close();
//調用打印機
newWindow.print();
//關閉newWindow頁面
newWindow.close();
}
myprint()調用方法:
myPrint(document.getElementById('printDivID'));
實例代碼:
<script>
function myPrint(obj){
var newWindow=window.open("打印窗口","_blank");
var docStr = obj.innerHTML;
newWindow.document.write(docStr);
newWindow.document.close();
newWindow.print();
newWindow.close();
}
</script>
<div id="print">
<hr />
打印演示區域,點擊打印后會在新窗口加載這里的內容!
<hr />
</div>
<button onclick="myPrint(document.getElementById('print'))">打 印</button>