tampermonkey 使用原生JS打印节点 不使用 jspdf 和 html2canvas等第三方库,带上原始节点的样式
时间: 2024-01-22 19:21:36 浏览: 152
可以使用原生JS的`window.print()`方法来打印节点,并且可以通过设置CSS样式来保留节点的原始样式。具体步骤如下:
1. 获取需要打印的节点
可以使用`document.querySelector()`或`document.getElementById()`等方法来获取需要打印的节点。
2. 创建一个隐藏的iframe元素
使用`document.createElement()`方法来创建一个`iframe`元素,并设置其样式为`display:none`,使其不可见。
```javascript
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
```
3. 将需要打印的节点添加到iframe中
将需要打印的节点添加到`iframe`中,通过设置`iframe`的`document`属性来访问其文档对象。
```javascript
document.body.appendChild(iframe);
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.body.appendChild(nodeToPrint);
```
4. 设置打印样式
在`iframe`的文档中设置打印样式,以保留节点的原始样式。
```javascript
var styleElement = iframeDocument.createElement('style');
styleElement.textContent = `
@media print {
* {
color: inherit !important;
background: transparent !important;
box-shadow: none !important;
}
${nodeToPrint.tagName} {
display: block !important;
}
}
`;
iframeDocument.head.appendChild(styleElement);
```
这里的样式规则将所有元素的颜色、背景和阴影都设置为继承,并将需要打印的节点设置为块级元素,以保证其在打印时的正常显示。
5. 打印节点
最后,调用`window.print()`方法来打印节点。
```javascript
iframe.contentWindow.focus();
iframe.contentWindow.print();
```
完整代码示例:
```javascript
var nodeToPrint = document.querySelector('#node-to-print');
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.body.appendChild(nodeToPrint);
var styleElement = iframeDocument.createElement('style');
styleElement.textContent = `
@media print {
* {
color: inherit !important;
background: transparent !important;
box-shadow: none !important;
}
${nodeToPrint.tagName} {
display: block !important;
}
}
`;
iframeDocument.head.appendChild(styleElement);
iframe.contentWindow.focus();
iframe.contentWindow.print();
```
阅读全文
相关推荐













