前端浏览器打印

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 2022-10-08 00:05  长安城下翩翩少年  阅读(74)  评论(0编辑  收藏  举报