window.print 頁面打印

定義和用法

print() 方法用於打印當前窗口的內容。javascript

語法

window.print();css

window.print() 實際上,是瀏覽器打印功能菜單的一種程序調用。與點擊打印功能菜單同樣,不能精確分頁,不能設置紙型,套打的問題更加無從談起,只不過,能夠讓用戶不用去點菜單,直接點擊網頁中的一個按鈕,或一個連接裏面調用罷了。事實上,不少用戶都是採用這種方式打印,可是這種方式最致命的缺點是不能設置打印參數,好比紙型,頁邊距,選擇打印機等等。html

方法一:
須要指出的是這種方法提供一個打印前和打印後的事件onbeforeprint、onafterprint。能夠在打印前的時候從新編輯一些格式,專門送去打印,打印後又處理回來。java

function window.onbeforeprint(){
   //將一些不須要打印的隱藏
}
function window.onafterprint(){
   //放開隱藏的元素
}

經過這兩個方法,就能夠實現頁面的部分打印。上述方法只有火狐和ie支持。css3

方法二:web

調用window.print()時,能夠利用css來控制頁面中的東西是否顯示chrome

<style>
@media print{
  .noprint{
     display:none
  }
}
</style>

HTML以下:
 瀏覽器

<table width="757" height="174" border="0" align="center" cellpadding="0" cellspacing="0">
 <tr class="noprint">
  <td height="133" align="center" valign="top">
   <img src="Images/top.jpg" width="757" height="133"></td>
 </tr>
</table>

注意:media的瀏覽器兼容問題。http://www.w3cschool.cc/cssref/css3-pr-mediaquery.htmlui

方法三:spa

點打印按鈕彈出新窗口,把須要打印的內容顯示到新窗口中,在新窗口中調用window.print()方法,而後自動關閉新窗口。若是要打印的頁面排版和原web頁面相差很大,採用此種方法。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>打印測完</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style>
	#oDiv2 div{width: 100px;height: 100px;border:1px solid #c50000;}
</style>
</head>
<body>
	<div>aaa</div>
	<div id='oDiv2'><div>bbb</div></div>
	<div>ccc</div>
	<input type="button" value="打印" id="js_print" />

	<script>

	var oPrintBtn = document.getElementById("js_print");
	var oDiv2 = document.getElementById("oDiv2");
	oPrintBtn.onclick=function(){
		var oPop = window.open('','oPop');
		var str = '<!DOCTYPE html>'
			str +='<html>'
			str +='<head>'
			str +='<meta charset="utf-8">'
			str +='<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">'
			str+='<style>';
			str+='#oDiv2 div{width: 100px;height: 100px;border:1px solid #c50000;}';
			str+='</style>';
			str +='</head>'
			str +='<body>'
			str +="<div id='oDiv2'><div>bbb</div></div>";
			str +='</body>'
			str +='</html>'

		oPop.document.write(str);
		oPop.print();
		oPop.close();
	}

	</script>
</body>
</html>

綜上 仍是第三種最靠譜

相關文章
相關標籤/搜索