JS實現頁面列印(整體、區域性)
我們在網頁開發過程中經常會有列印頁面的需求,通過JS來實現的方法有很多,這裡我做了一個整理,供大家參考。
方式一:window.print()
整體列印
?1 |
<
a
href
=
"javascrīpt:window.print()" rel
=
"external nofollow"
target
=
"_self"
>列印</
a
>
|
現在就輕鬆實現了頁面的列印,但是這種方式會將整個頁面列印,如果想要實現指定區域的列印需要通過下面的設定
區域性列印
首先,在html中,通過star和end來標記列印區域
1 2 3 4 5 6 7 8 |
<
h1
>這塊內容不需要列印</
h1
>
<!--startprint-->
<
div
class
=
"content"
>
這裡是需要列印的內容
.....
</
div
>
<!--endprint-->
<
h1
>這塊內容不需要列印</
h1
>
|
然後,在點選事件中新增如下程式碼
?1 2 3 4 5 6 7 8 9 |
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();
}
|
過濾列印區域的內容
例如
?1 2 3 4 5 6 7 8 |
<!--startprint-->
<
div
class
=
"content"
>
<
button
class
=
"noprint"
>預覽</
button
>
<
button
class
=
"noprint"
>列印</
button
>
這裡是需要列印的內容
.....
</
div
>
<!--endprint-->
|
上面的預覽和列印按鈕不希望列印,如果要過濾的話可以做下面的樣式設定
?1 2 3 4 5 6 7 |
<style type=
"text/css"
>
@media
print
{
.noprint{
display
:
|