咱也不知道,咱也不敢问啊
照搬这函数就得了
function printPartial(dom, { title= document.title,}= {}) {
if (!dom) return;
let copyDom = document.createElement('span');
const styleDom = document.querySelectorAll('style, link, meta');
const titleDom = document.createElement('title');
titleDom.innerText = title;
copyDom.appendChild(titleDom);
Array.from(styleDom).forEach(item=> {
copyDom.appendChild(item.cloneNode(true));
});
copyDom.appendChild(dom.cloneNode(true));
const htmlTemp = copyDom.innerHTML;
copyDom = null;
const iframeDom = document.createElement('iframe');
const attrObj = {
height: 0,
width: 0,
border: 0,
wmode: 'Opaque'
};
const styleObj = {
position: 'absolute',
top: '-999px',
left: '-999px',
};
Object.entries(attrObj).forEach(([key, value])=> iframeDom.setAttribute(key, value));
Object.entries(styleObj).forEach(([key, value])=> iframeDom.style[key] = value);
document.body.insertBefore(iframeDom, document.body.children[0]);
const iframeWin = iframeDom.contentWindow;
const iframeDocs = iframeWin.document;
iframeDocs.write(<!doctype html>
);
iframeDocs.write(htmlTemp);
iframeWin.focus();
iframeWin.print();
document.body.removeChild(iframeDom);
}
调用函数--传入dom对象
printPartial(document.querySelector('#description'));
这里设置打印的样式
<style media="print">
这个是去掉页眉、页脚
@page {
size: auto; /* auto is the initial value /
margin: 0mm; / this affects the margin in the printer settings */
}
</style>
转自【Jsonz】https://juejin.im/post/5b371a8a6fb9a00e5326f06c
网友评论