javascript – 是否有一种从HTML页面打印div的方式?

前端之家收集整理的这篇文章主要介绍了javascript – 是否有一种从HTML页面打印div的方式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个html页面使用AngularJS,我想打印一个div.有没有一种方式呢? ..或者它只是经典的 JavaScript方式如下:
  1. <script language="javascript" type="text/javascript">
  2. function printDiv(divID) {
  3. //Get the HTML of div
  4. var divElements = document.getElementById(divID).innerHTML;
  5. //Get the HTML of whole page
  6. var oldPage = document.body.innerHTML;
  7.  
  8. //Reset the page's HTML with div's HTML only
  9. document.body.innerHTML =
  10. "<html><head><title></title></head><body>" +
  11. divElements + "</body>";
  12.  
  13. //Print Page
  14. window.print();
  15.  
  16. //Restore orignal HTML
  17. document.body.innerHTML = oldPage;
  18. }
  19. </script>

如果AngularJS没有任何东西,你可以建议o做这样的方式,而不使用JavaScript函数(例如:doc.getElementById())..接近AngularJS的方法

谢谢,

解决方法

我已经使用iframe技术创建了一个用于打印div内容的简单指令.这有点黑客,但效果很好.在我看来,没有更好的办法来做到这一点.指令脚本是:
  1. 'use strict';
  2.  
  3. angular.module('yourAppNameHere').directive('printDiv',function () {
  4. return {
  5. restrict: 'A',link: function(scope,element,attrs) {
  6. element.bind('click',function(evt){
  7. evt.preventDefault();
  8. PrintElem(attrs.printDiv);
  9. });
  10.  
  11. function PrintElem(elem)
  12. {
  13. PrintWithIframe($(elem).html());
  14. }
  15.  
  16. function PrintWithIframe(data)
  17. {
  18. if ($('iframe#printf').size() == 0) {
  19. $('html').append('<iframe id="printf" name="printf"></iframe>'); // an iFrame is added to the html content,then your div's contents are added to it and the iFrame's content is printed
  20.  
  21. var mywindow = window.frames["printf"];
  22. mywindow.document.write('<html><head><title></title><style>@page {margin: 25mm 0mm 25mm 5mm}</style>' // Your styles here,I needed the margins set up like this
  23. + '</head><body><div>'
  24. + data
  25. + '</div></body></html>');
  26.  
  27. $(mywindow.document).ready(function(){
  28. mywindow.print();
  29. setTimeout(function(){
  30. $('iframe#printf').remove();
  31. },2000); // The iFrame is removed 2 seconds after print() is executed,which is enough for me,but you can play around with the value
  32. });
  33. }
  34.  
  35. return true;
  36. }
  37. }
  38. };
  39. });

在您的模板中,您可以将打印按钮标记为:

  1. <a href="#" print-div=".css-selector-of-the-div-you-want-to-print">Print!</a>

就是这样,它应该工作.
黑客的部分是,iFrame在一定数量的毫秒之后被删除,因为没有跨浏览器的方式来检测打印执行的结束,所以你需要多少时间来运行它.

您可能需要包含jQuery才能正常工作,我不知道如果没有它,我几乎不会工作.我添加了一些内联意见,使事情更清晰.我使用了一些this answer中使用弹出窗口来打印div内容代码(但在Angular.js之外).也许你会更喜欢这种方法.

猜你在找的JavaScript相关文章