日韩精品成人无码专区免费-国产99久久久久久免费看-国产精品丝袜久久久久久不卡-国产精品无码一区二区三区

代碼示例js實現瀏覽器打印功能

發布時間:2025-06-28 點擊:31
最近接觸到一個新需求,實現打印機打印小票的功能。打的一桌子小票(慚愧),不過也基本滿足了業務上的需求,現在分享一下如何實現(好記性不如爛筆頭)
先上代碼
// 布局代碼<p id="print"> <p id="print_content"></p></p>//js 部分代碼var f = document.getelementbyid('printf'); if (f) { document.getelementbyid("print_content").removechild(f); } var printhtml = ` <p style="font-size:12px;margin-left: -6px;"> <p style="margin-left:40px;">${this.ticket.title}</p> <p>--------------------------------------</p> <p>提貨點:${this.ticket.pickupaddress}</p> <p>商品名稱:${this.ticket.commodityname}</p> <p>下單時間:${this.ticket.paymenttime}</p> <p>提貨人:${this.ticket.receiver}</p> <p>聯系電話:${this.ticket.receiverphone}</p> <p>提貨碼:${this.ticket.pickupcode}</p> <p>提貨時間:${this.ticket.submissiontime}</p> <p style="color:#ffffff">.</p> </p>` if (!!window.activexobject || "activexobject" in window) { // 針對ie進行適配 var hkey_root, hkey_path, hkey_key; hkey_root = "hkey_current_user"; hkey_path = "\\\\\\\\software\\\\\\\\microsoft\\\\\\\\internet explorer\\\\\\\\pagesetup\\\\\\\\"; //設置網頁打印的頁眉頁腳為空 function pagesetup_null() { var wsh = new activexobject("wscript.shell"); hkey_key = "header"; wsh.regwrite(hkey_root hkey_path hkey_key, ""); hkey_key = "footer"; wsh.regwrite(hkey_root hkey_path hkey_key, ""); hkey_key = "margin_left" wsh.regwrite(hkey_root hkey_path hkey_key, "0"); //鍵值設定--左邊邊界 hkey_key = "margin_top" wsh.regwrite(hkey_root hkey_path hkey_key, "0"); //鍵值設定--上邊邊界 hkey_key = "margin_right" wsh.regwrite(hkey_root hkey_path hkey_key, "0"); //鍵值設定--右邊邊界 hkey_key = "margin_bottom" wsh.regwrite(hkey_root hkey_path hkey_key, "0"); //鍵值設定--下邊邊界 } printhtml = ` <p style="font-size:12px;font-weight: 800;height:150px;width:300px"> <p style="margin-left:35px">${this.ticket.title}</p> <p>------------------------------------------------</p> <p>提貨點:${this.ticket.pickupaddress}</p> <p>商品名稱:${this.ticket.commodityname}</p> <p>下單時間:${this.ticket.paymenttime}</p> <p>提貨人:${this.ticket.receiver}</p> <p>聯系電話:${this.ticket.receiverphone}</p> <p>提貨碼:${this.ticket.pickupcode}</p> <p>提貨時間:${this.ticket.submissiontime}</p> <p style="color:#ffffff;font-weight: 100;">.</p> </p>` } var iframe = document.createelement('iframe'); iframe.id = 'printf'; iframe.style.width = '0'; iframe.style.height = '0'; iframe.style.border = "none"; document.getelementbyid("print_content").appendchild(iframe); settimeout(() => { iframe.contentdocument.write(printhtml); iframe.contentdocument.close(); iframe.contentwindow.focus(); iframe.contentwindow.print(); }, 100)因為要求不能把打印的數據顯示在頁面上,所以通過iframe的方式去實現。單純的截取字符串重新賦值body內容能進行打印卻把打印的內容展現在頁面中了,所以不行。
打印針對ie的瀏覽器進行了一定程度的調整,ie打印要做特定的處理,詳見上面判斷代碼。打印內容通過模板字符串加內聯樣式去實現。滿足了基本需求。
是否應該也通過截取頁面字符串的方式去做可能比較浪費性能些,為什么這么說?因為樣式在打印的小票上有一定程度的偏差,修了東墻破了西墻,只能采取相對的方式取舍。如果這種寫法不滿足,可以采取截取字符串寫class嘗試。
相關學習推薦:javascript視頻教程

云服務器系統盤滿導致桌面文件不見了的處理方法
云服務器怎么用本地文件夾
域名及郵箱-企業郵局
華為云服務器上部署網站
阿里云服務器拼團價格
做產品就是一場“權力的游戲”
收到下圖郵件請問是什么原因
云服務器里修改網站