// 建立一個div用來存放打印的內容 let dom = document.createElement("div"); // html須要打印的內容按照需求本身定義內容和樣式 let html = `<div id="printContent" style="width: 210mm;}"></div>`; // 將html放入div dom.innerHTML = html; // 建立一個iframe並制定樣式和屬性 let 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; return ""; }); // 將iframe插入到頁面id爲app的標籤前面 document.body.insertBefore(iframeDom, document.getElementById("app")); // 獲取到iframe中的window對象 let iframeWin = iframeDom.contentWindow; let iframeDocs = iframeWin.document; iframeDocs.write(`<!doctype html>`); iframeDocs.write(dom.innerHTML); iframeWin.print(); setTimeout(() => { document.body.removeChild(iframeDom); }, 1000);