window.print()打印html網(wǎng)頁的兩種方法實現(xiàn)
一、編輯打印區(qū)域
思路:
通過編輯打印的開始、結(jié)束標(biāo)記來區(qū)分打印的區(qū)域
HTML:
<!--startprint--> <div>打印的區(qū)域</div> <!--endprint-->
js:
function doPrint() { bdhtml=window.document.body.innerHTML; sprnstr="<!--startprint-->"; //開始打印標(biāo)識字符串有17個字符 eprnstr="<!--endprint-->"; //結(jié)束打印標(biāo)識字符串 prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17); //從開始打印標(biāo)識之后的內(nèi)容 prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr)); //截取開始標(biāo)識和結(jié)束標(biāo)識之間的內(nèi)容 window.document.body.innerHTML=prnhtml; //把需要打印的指定內(nèi)容賦給body.innerHTML window.print(); //調(diào)用瀏覽器的打印功能打印指定區(qū)域 window.document.body.innerHTML=bdhtml;//重新給頁面內(nèi)容賦值; return false; }
二:將不需要打印的部分隱藏
思路:
在打印之前利用jQuery的$(selector).hide(speed,callback)語法將不需要的元素先隱藏,打印之后再將隱藏的元素顯示出來$(selector).show(speed,callback)
HTML:
<button class="btn btn-primary" style="width: 85px;height: 40px;margin-left: 25px;" onclick="doPrint_hide()"> 打印 </button> <div class="tab_out1 hide_when_print"> 11111 </div> <div class="everyCustomer_list"> 22222 </div> <div class="form-horizonta hide_when_print"> 3333 </div>
js:
<script> function doPrint_hide() { window.print() } $(function () { var beforePrint = function () { //將需要打印的元素上加一個 hide_when_print類(可以隨便定義),這個類是專門控制顯示隱藏的 $(".hide_when_print").hide() console.log('打印前'); //設(shè)置打印時的頁面的樣式 document.getElementsByTagName('body')[0].style.zoom = 1.10; var css = { 'display': 'flex', 'flex-direction': 'column', 'justify-content': 'center', 'flex-wrap': 'wrap', }; var css1 = { "margin": '2px auto' } var css2 = { 'border': "0" } $("#tab_out1").css(css) $(".everyCustomer_list").css(css1) $(".form-horizontal").css(css2) }; var afterPrint = function () { console.log('打印后'); document.getElementsByTagName('body')[0].style.zoom = 1.00; //顯示之前被隱藏的元素 $(".hide_when_print").show(); //設(shè)置打印后的樣式 var css = { 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'flex-start', 'flex-wrap': 'wrap', }; var css1 = { 'margin': '0', 'margin-left': '12px', 'margin-top': '20px' } var css2 = { 'border': "1px solid #e7e7eb" } $("#tab_out1").css(css); $(".everyCustomer_list").css(css1); $(".form-horizontal").css(css2) }; if (window.matchMedia) { var mediaQueryList = window.matchMedia('print'); mediaQueryList.addListener(function (mql) { if (mql.matches) { beforePrint(); } else { afterPrint(); } }); } window.onbeforeprint = beforePrint; window.onafterprint = afterPrint; }) </script>
到此這篇關(guān)于window.print()打印html網(wǎng)頁的兩種方法實現(xiàn)的文章就介紹到這了,更多相關(guān)window.print()打印html網(wǎng)頁內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
window.parent調(diào)用父框架時 ie跟火狐不兼容問題
window.parent調(diào)用父框架時,ie跟火狐不兼容問題!2009-07-07