JavaScriptはDivの内容を印刷します.
2959 ワード
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
</div>
<div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
</div>
<input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
</body>
</html>
印刷したウェブページの設定がCSSスタイルファイルを参照している場合、スタイルファイルを導入する必要があります.修正した方法は以下の通りです.
function printDiv(divID,title) {
var links = document.getElementsByTagName("link");
var styleContent = "";
for (var i = 0, l = links.length; i < l; i++) {
var src = links[i].href;
styleContent += "<link href=\"" + src + "\" rel=\"stylesheet\" type=\"text/css\" />";
}
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
var titleDiv = "<div style=\"text-align:center;width:100%;\"><h2>" + title + "</h2></div>";
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title> </title>" + styleContent + "</head><body>" + titleDiv +
divElements + "</body>";
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}