js局部打印

局部打印的原理:
一、將局部的div等元素的outHTML的值賦給一個新的頁面。
二、結果發現局部元素的css樣式沒有引用過來,致使頁面混亂。須要將css一同引用過來。
三、調用window.print()進行打印的時候,發現html字符串中寫入了script,報錯。須要加一個空字符串變量來隔斷。javascript

<img src="../images/dayin.gif" style="cursor:hand" onclick="myPrint('div1','css1')" />
<div id="div1" class="div1">div裏的內容</div>
<script type="text/javascript">
function myPrint(objID, cssName) {
var newWindow = window.open("打印窗口", "_blank"); //新建一個頁面
var str = "";
//將須要局部打印的id傳入,而後再加上須要用到的樣式。最終採用了script的window.print進行打印。
//在html字符串中不能直接寫script,會報錯,只能在中間加入一個空字符串進行斷開。
var docStr = "<html><head><title>打印</title><link rel=\"stylesheet\" type=\"text/css\" href=\"../css/" + cssName + ".css\" /></head><body>" + document.getElementById(objID).outerHTML + "</body><scr" + str + "ipt>window.print();</scr" + str + "ipt></html>";
newWindow.document.write(docStr);
newWindow.document.close();
}
</script>css

相關文章
相關標籤/搜索