美文网首页
自定义打印区域/打印内容

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

作者: 起个蓝筹海名字啊 | 来源:发表于2019-04-17 16:28 被阅读0次

    咱也不知道,咱也不敢问啊
    照搬这函数就得了
    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 —— 浏览器打印扫盲

    相关文章

      网友评论

          本文标题:自定义打印区域/打印内容

          本文链接:https://www.haomeiwen.com/subject/wpvnwqtx.html