UNPKG

@pit-front-end/utils

Version:

湖南创智艾泰克科技有限公司

2 lines (1 loc) 2.14 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class s{constructor(t,e){if(this.options={},this.dom=null,!(this instanceof s))return new s(t,e);this.options=this.extend({noPrint:".no-print"},e),typeof t=="string"?this.dom=document.querySelector(t):(this.isDOM(t),this.dom=this.isDOM(t)?t:t.$el),this.init()}init(){const t=this.getStyle()+this.getHtml();this.writeIframe(t)}getHtml(){const t=document.querySelectorAll("input"),e=document.querySelectorAll("textarea"),i=document.querySelectorAll("select");for(let n=0;n<t.length;n++)t[n].type=="checkbox"||t[n].type=="radio"?t[n].checked==!0?t[n].setAttribute("checked","checked"):t[n].removeAttribute("checked"):(t[n].type=="text",t[n].setAttribute("value",t[n].value));for(let n=0;n<e.length;n++)e[n].type=="textarea"&&(e[n].innerHTML=e[n].value);for(let n=0;n<i.length;n++)if(i[n].type=="select-one"){const o=i[n].children;for(const r in o)o[r].tagName=="OPTION"&&(o[r].selected==!0?o[r].setAttribute("selected","selected"):o[r].removeAttribute("selected"))}return this.dom.outerHTML}getStyle(){let t="";const e=document.querySelectorAll("style,link");for(let i=0;i<e.length;i++)t+=e[i].outerHTML;return t+="<style>"+(this.options.noPrint?this.options.noPrint:".no-print")+"{display:none;}</style>",t}extend(t,e){for(const i in e)t[i]=e[i];return t}isDOM(t){return typeof HTMLElement=="object"?function(e){return e instanceof HTMLElement}:function(e){return e&&typeof e=="object"&&e.nodeType===1&&typeof e.nodeName=="string"}}toPrint(t){try{setTimeout(function(){t.focus();try{t.document.execCommand("print",!1,null)||t.print()}catch{t.print()}t.close()},10)}catch(e){console.warn("err",e)}}writeIframe(t){var r;const e=document.createElement("iframe"),i=document.body.appendChild(e);e.id="myIframe",e.setAttribute("style","position:absolute;width:0;height:0;top:-10px;left:-10px;");const n=i.contentWindow||i.contentDocument,o=i.contentDocument||((r=i.contentWindow)==null?void 0:r.document);o==null||o.open(),o==null||o.write(t),o==null||o.close(),e.onload=()=>{this.toPrint(n),setTimeout(function(){document.body.removeChild(e)},100)}}}exports.Print=s;