window.print() 打印指定内容
时间: 2023-09-22 20:08:25 浏览: 189
如果需要打印页面中的指定内容,可以使用 HTML 的打印样式表(@media print)。这样可以在打印时隐藏不需要打印的内容,并且格式化需要打印的内容。下面是一个示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Print Example</title>
<style>
@media print {
.no-print {
display: none;
}
}
</style>
</head>
<body>
<h1 class="no-print">Print Example</h1>
<p class="no-print">This is an example of printing an HTML page using JavaScript.</p>
<div id="print-content">
<p>This is the content to be printed.</p>
</div>
<button class="no-print" onclick="printContent()">Print</button>
<script>
function printContent() {
var content = document.getElementById("print-content").innerHTML;
var printWindow = window.open('', '', 'height=400,width=800');
printWindow.document.write('<html><head><title>Print Content</title></head><body>');
printWindow.document.write(content);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
}
</script>
</body>
</html>
```
在上面的示例中,我们在 HTML 中定义了一个样式表(@media print),用于在打印时隐藏指定的元素(在本例中是标题和说明)。然后我们在页面中定义了一个需要打印的内容(在本例中是一个 div 元素),并且给这个 div 元素添加了一个 id(print-content)。接着我们定义了一个打印按钮,并且给按钮添加一个 onclick 事件,该事件会调用 printContent() 函数。
在 printContent() 函数中,首先获取需要打印的内容(即 print-content 元素的 innerHTML),然后创建一个新的浏览器窗口(使用 window.open() 方法)。接着我们在新窗口中写入需要打印的内容,并且调用 print() 方法进行打印。
需要注意的是,在新窗口中写入 HTML 代码时,需要在 head 标签中添加 title 标签,否则在某些浏览器中可能无法正常打印。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)