随笔 - 148  文章 - 0  评论 - 13  阅读 - 21万

前端浏览器打印

window.print()

    const bodyHtml = document.body.innerHTML
    document.body.innerHTML= $0.innerHTML
    window.print();
    document.body.innerHTML = bodyHtml
    location.reload(); // 刷新页面

$0 为打印的节点;location.reload() 为了解决dom事件没有绑定的问题。

但是重新刷新页面,对翻页,搜索后的数据要重新进行操作,用户体验不好。所以能不能实现,不用刷新页面也能重新将事件绑定回去。

利用iframe 进行打印

function do_print(id_str){
      var el = document.getElementById(id_str);
      var iframe = document.createElement('IFRAME');
      var doc = null;
      iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
      document.body.appendChild(iframe);
      doc = iframe.contentWindow.document;
      // 引入打印的专有CSS样式,根据实际修改
      doc.write("<LINK rel=\"stylesheet\" type=\"text/css\" href=\"css/print.css\">");
      doc.write('<div>' + el.innerHTML + '</div>');
      doc.close();
      iframe.contentWindow.focus();
      iframe.contentWindow.print();
      if (navigator.userAgent.indexOf("MSIE") > 0)
      {
           document.body.removeChild(iframe);
      }
}
posted on   长安城下翩翩少年  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示