HTML打印指定DIV

思路一:创建新的窗口,在新窗口内生成div内容进行打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>打印指定区域</title>
</head>
<body>

<div>
<button onclick="printDiv()">打印指定内容</button>
</div>

<div id="printArea">
<h2>这是需要打印的内容</h2>
<p>这里的内容将会被打印。</p >
</div>

<div>
<p>这里是不会被打印的内容。</p >
</div>

<script>
function printDiv() {
var divContent = document.getElementById("printArea").innerHTML;
var newWindow = window.open('', '', 'width=800,height=600');
newWindow.document.write('<html><head><title>打印</title></head><body>');
newWindow.document.write(divContent);
newWindow.document.write('</body></html>');
newWindow.document.close();
newWindow.print();
}
</script>

</body>
</html>

思路二:隐藏非打印区域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>

<head>
<style>
.printview {
background-color: #fff;
padding: 1rem;
min-height: calc(100vh);
}

@media print {
.printview-open {
overflow: auto !important;
}

.printview-open>*:not(.printview) {
display: none !important;
}
}
</style>
</head>

<body>
<div>hello world!</div>
<div id="pdiv" >
print this div
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
</div>
<div>
-------
<ul>
<li>444</li>
<li>555</li>
<li>666</li>
</ul>
</div>

<button onclick="div_print('pdiv')">print</button>
<script>
function div_print(divID) {
var divContent = document.getElementById(divID).innerHTML;

const printContent = divContent
const body = document.querySelector('body')
body.classList.add('printview-open')
const dialog = document.createElement('div')
dialog.classList.add('printview')
dialog.innerHTML = printContent
body.appendChild(dialog)
window.print()
setTimeout(() => {
console.log('print dlg over');
body.classList.remove('printview-open')
dialog.remove()
}, 100)
}
</script>
</body>

</html>