@pit-front-end/utils
Version:
湖南创智艾泰克科技有限公司
81 lines (80 loc) • 2.75 kB
JavaScript
class r {
constructor(t, e) {
if (this.options = {}, this.dom = null, !(this instanceof r)) return new r(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 s in o)
o[s].tagName == "OPTION" && (o[s].selected == !0 ? o[s].setAttribute("selected", "selected") : o[s].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 s;
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 || ((s = i.contentWindow) == null ? void 0 : s.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);
};
}
}
export {
r as Print
};