js調用iframe實現列印頁面內容的方法

來源:互聯網
上載者:User

js調用iframe實現列印頁面內容的方法

 這篇文章主要介紹了js調用iframe實現列印頁面內容的方法,需要的朋友可以參考下

1、程式說明

 

1) 此程式可以實現選擇頁面中的地區進行列印,以iframe方式進行列印;

2) 與原生態的print() 區別在於,取消列印頁面後可以完整保留當前訪問頁面的內容。

 

2、代碼部分

 

1) JS 函數:

 代碼如下:

function do_print(id_str)//id-str 列印範圍的id

{

var el = document.getElementById(id_str);

var iframe = document.createElement('IFRAME');

var doc = null;

iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');

document.body.appendChild(iframe);

doc = iframe.contentWindow.document;

// 引入列印的專有CSS樣式,www.111Cn.net根據實際修改

doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");

doc.write('<div>' + el.innerHTML + '</div>');

doc.close();

iframe.contentWindow.focus();

iframe.contentWindow.print();

if (navigator.userAgent.indexOf("MSIE") > 0)

{

     document.body.removeChild(iframe);

}

}

 

 

2) HTML:

 

代碼如下:

// 列印範圍:

<div id="print_box">

......

</div>

// 調用列印

<button onclick="javascript:do_print('print_box');">列印</button>

 

 

3. 測試

 

點擊頁面上的列印按鈕,即可測試列印;

 

除了上面方法我們還可以通過jquery來執行個體,代碼如下

 

代碼如下:

<script type="text/javascript" src="jquery-1.4.2.min.js"></script> 

<script type="text/javascript" src="jquery.PrintArea.js"></script> 

<script>

$(document).ready(function(){

  $("input#biuuu_button").click(function(){

 

  $("div#myPrintArea").printArea();

 

});

});

</script>

<input id="biuuu_button" type="button" value="列印"></input>

<div id="myPrintArea">.....文本列印部分.....</div>

 

 

 

如果要實現地區列印我們可嘗試下面方法

 

下面本文分享一種超簡單的方法實現頁面的列印功能,不僅可以列印整個頁面,還可以列印頁面某塊地區

 

代碼如下:

<html>

<head>

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

<script language="javascript">

function printdiv(printpage){

 var headstr="<html><head><title></title></head><body>";

 var footstr="</body>";

 var newstr=document.all.item(printpage).innerHTML;

 var oldstr=document.body.innerHTML;

 document.body.innerHTML=headstr+newstr+footstr;

 window.print(); 

 document.body.innerHTML=oldstr;

 return false;

}

</script>

<title>div print</title>

</head>

<body>

<input type="button" onClick="printdiv('div_print');" value=" 列印 ">

<div id="div_print">

<h1 style="Color:Red">被列印範圍:www.jb51.net</h1>

</div>

這塊地區是列印不到的!

</body>

</html>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.