tampermonkey 使用原生JS打印节点 不使用 jspdf 和 html2canvas等第三方库,带上原始节点的样式
时间: 2024-01-22 22:21:32 浏览: 24
可以使用原生JS的 `window.print()` 方法来打印节点,但是这种方法只能打印当前页面的内容,无法自定义打印的节点和样式。如果需要自定义打印的节点和样式,可以使用以下步骤:
1. 创建一个空白页面,并在其中引入需要打印的节点和样式。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Print Preview</title>
<style>
/* 在这里添加需要打印的样式 */
</style>
</head>
<body>
<!-- 在这里添加需要打印的节点 -->
</body>
</html>
```
2. 使用 `window.open()` 方法打开空白页面,并将需要打印的节点和样式传递给它。
```javascript
var printWindow = window.open('', '', 'height=500,width=500');
printWindow.document.write('<html><head><title>Print Preview</title>');
printWindow.document.write('</head><body>');
printWindow.document.write(document.getElementById('print-content').innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.focus();
```
其中 `print-content` 是需要打印的节点的 id。
3. 在新打开的页面中调用 `window.print()` 方法进行打印。
```javascript
printWindow.print();
```
完整的代码如下:
```javascript
var printWindow = window.open('', '', 'height=500,width=500');
printWindow.document.write('<html><head><title>Print Preview</title>');
printWindow.document.write('<style>');
printWindow.document.write(document.getElementById('print-styles').innerHTML);
printWindow.document.write('</style></head><body>');
printWindow.document.write(document.getElementById('print-content').innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
```
注意:在打印时,浏览器会自动去掉一些样式,如背景色和背景图片等。如果需要打印完整的样式,可以尝试使用第三方库,如 jspdf 和 html2canvas。