怎么用iframe实现前端浏览器打印

2023-05-26

这篇文章主要讲解了“怎么用iframe实现前端浏览器打印”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用iframe实现前端浏览器打印”吧!

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);
      }
}

感谢各位的阅读,以上就是“怎么用iframe实现前端浏览器打印”的内容了,经过本文的学习后,相信大家对怎么用iframe实现前端浏览器打印这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是本站,小编将为大家推送更多相关知识点的文章,欢迎关注!

《怎么用iframe实现前端浏览器打印.doc》

下载本文的Word格式文档,以方便收藏与打印。