自定义打印区域/打印内容

咱也不知道,咱也不敢问啊
照搬这函数就得了
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

window.print —— 浏览器打印扫盲

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。