1. 程式人生 > >js網頁列印指定區域內容

js網頁列印指定區域內容

方法一:

 <script language="javascript" type="text/javascript">

    function printpage(myDiv){
  
    //var newstr = document.all.item(myDiv).innerHTML;
    var newstr = document.getElementById(myDiv).innerHTML;
     alert(newstr);
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = newstr;
    window.print();
    document.body.innerHTML = oldstr;
    return false;
    } 
    </script>

   <div id="myDiv"  >說明:列印整個div區域的內容,如果包含按鈕,則按鈕也會打印出來!
    <div>
      列印內容列印內容列印內容列印內容列印內容列印內容列印內容列印內容
    adfhioasdhfiohasdofihosdhfosdhfiosdhfiosdfhsdfhsdifsidfiosdfhosdhf
        </div>
    <input type="button" id="bt" onclick="javascript:printpage('myDiv')"   value="列印" />
    </div>

方法二:

<script language="javascript" type="text/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>

<div>
    <!--startprint-->說明:這是開始列印的位置
    列印內容列印內容列印內容列印內容列印內容列印內容列印內容列印內容
    adfhioasdhfiohasdofihosdhfosdhfiosdhfiosdfhsdfhsdifsidfiosdfhosdhf
    <!--endprint-->說明:這是結束列印的位置
    </div>
    <input type="button" id="bt" onclick="javascript:doPrint()"   value="列印" />
    </div>

使用者在列印網頁的時候,頁面上會出現網頁的名字,頁碼,連結地址和列印時間,如果使用者不需要這些資訊,則需要設定使用者的網頁設定:

具體如下:檔案-》頁面設定-》將頁首頁尾中的程式碼刪除即可。打印出來的文件沒有頁碼資訊和連結地址資訊