JavaScript打印網(wǎng)頁指定區(qū)域的例子
更新時間:2014年05月03日 10:07:19 作者:
這篇文章主要介紹了JavaScript打印網(wǎng)頁指定區(qū)域的例子,需要的朋友可以參考下
JavaScript打印頁面指定div區(qū)域原理:使用window.open()在瀏覽器打開一個新的頁面(window), 使用 window.document.write()將指定div區(qū)域的內(nèi)容寫入新窗口文檔,document.close()關(guān)閉文檔,使用window.print()調(diào)用打印機(jī)打印當(dāng)前文檔。
JavaScript打印函數(shù)myPrint(obj):
復(fù)制代碼 代碼如下:
function myPrint(obj){
//打開一個新窗口newWindow
var newWindow=window.open("打印窗口","_blank");
//要打印的div的內(nèi)容
var docStr = obj.innerHTML;
//打印內(nèi)容寫入newWindow文檔
newWindow.document.write(docStr);
//關(guān)閉文檔
newWindow.document.close();
//調(diào)用打印機(jī)
newWindow.print();
//關(guān)閉newWindow頁面
newWindow.close();
}
myprint()調(diào)用方法:
復(fù)制代碼 代碼如下:
myPrint(document.getElementById('printDivID'));
實(shí)例代碼:
復(fù)制代碼 代碼如下:
<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 />
打印演示區(qū)域,點(diǎn)擊打印后會在新窗口加載這里的內(nèi)容!
<hr />
</div>
<button onclick="myPrint(document.getElementById('print'))">打 印</button>
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 />
打印演示區(qū)域,點(diǎn)擊打印后會在新窗口加載這里的內(nèi)容!
<hr />
</div>
<button onclick="myPrint(document.getElementById('print'))">打 印</button>
相關(guān)文章
輕松實(shí)現(xiàn)js選項(xiàng)卡切換效果
這篇文章主要幫助大家輕松實(shí)現(xiàn)js選項(xiàng)卡切換效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09javascript回調(diào)函數(shù)的概念理解與用法分析
這篇文章主要介紹了javascript回調(diào)函數(shù)的概念理解與用法,結(jié)合具體實(shí)例形式分析了javascript回調(diào)函數(shù)的功能、原理、使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-05-05