1. 程式人生 > >[自用門戶]js 列印網頁中指定的部分內容和範圍

[自用門戶]js 列印網頁中指定的部分內容和範圍

列印網頁中定義的部分內容的實現方法

正常情況下的列印是使用 window.print();直接整頁列印,但如果需要列印網頁中定義的部分內容,則可使用如下的方法:

1、在頁面的程式碼頭部處加入JavaScript:

function doPrint() { 

bdhtml=window.document.body.innerHTML; 

sprnstr="<!--startprint-->";//開始列印標識字串有17個字元

eprnstr="<!--endprint-->";//結束列印標識字串

prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);//從開始列印標識之後的內容

prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//擷取開始標識和結束標識之間的內容

window.document.body.innerHTML=prnhtml;//把需要列印的指定內容賦給body.innerHTML

window.print(); //呼叫瀏覽器的列印功能列印指定區域

window.document.body.innerHTML=bdhtml; //最後還原頁面

}

</script>

2、在頁面正文處加上<!--startprint-->與<!--endprint-->標識。

也就是在需要使用者列印儲存的正文所對應的html處附加上。同時,如果採用小偷程式獲得遠端資料並需列印,可將此等資料置於該定義標籤之內即可。

3、擷取內容部分已完成,現在加個“列印”的連結:

<a href="javascript:;"onClick="doPrint()">列印</a>

<scriptlanguage=javascript>

function doPrint() { 

bdhtml=window.document.body.innerHTML; 

sprnstr="<!--startprint-->"; 

eprnstr="<!--endprint-->"; 

prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17); 

prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr)); 

window.document.body.innerHTML=prnhtml; 

window.print(); 

}

</script>

要列印的內容在<!--startprint-->startprint與endprint之間的區域<!--endprint-->裡。

<a href="javascript:;"onClick="doPrint()">列印</a>

本貼來自天極網群樂社群--http://q.yesky.com/group/review-17575085.html

第二種做法:

<html>

<meta http-equiv="Content-Type"content="text/html; charset=utf-8" />

<scripttype="text/javascript">

  <!--

              //自動在列印之前執行

   window.onbeforeprint = function(){

       $("#test").hide();

   }

   //自動在列印之後執行

    window.onafterprint= function(){

       $("#test").show();

    }

  //-->

</script>

<body >

    <divid="test">這段文字不會被打印出來</div>

  <input type="button"onclick="window.print();" value="列印本頁" />

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<DIV>

列印區域內容

</DIV>

</body>

</html>