通过JQuery打印DIV内容

假设我的页面中有很多div,但我想使用jquery打印特定div的内容。 我发现有一个插件。

jQuery打印元素

使用此插件我们可以轻松打印如下所示的div内容。

$('SelectorToPrint').printElement(); 

但如果我的div隐藏在页面中会发生什么。 那么它是否有效 这个插件可以打印隐藏div的内容吗?

如果打印机没有连接客户端机器会发生什么。 我想显示消息,如果打印机不存在“未找到打印机”的客户? 如何处理这种情况。 所以请告诉我什么是在页面中打印隐藏div的内容的最佳方法,以及如果没有附加打印机则处理打印机问题。

谢谢

你的问题听起来不像是你自己尝试过,所以我甚至不应该想到回答,但是:如果一个隐藏的div不能打印出那一行:

 $('SelectorToPrint').printElement(); 

只需将其更改为:

 $('SelectorToPrint').show().printElement(); 

这应该使它在所有情况下都有效。

其余的,没有解决方案。 该插件将为您打开打印对话框,用户必须选择他的打印机。 你根本无法确定打印机是否附带了javascript(而且你(几乎)没有打印对话框就无法打印 – 如果你正在考虑这个问题)。

注意:

$.browser对象已在jQuery版本1.9.x中删除,使得此库不受支持。

我更喜欢这个,我测试了它和它的工作

https://github.com/jasonday/printThis

 $("#mySelector").printThis(); 

要么

 $("#mySelector").printThis({ * debug: false, * show the iframe for debugging * importCSS: true, * import page CSS * printContainer: true, * grab outer container as well as the contents of the selector * loadCSS: "path/to/my.css", * path to additional css file * pageTitle: "", * add title to print page * removeInline: false * remove all inline styles from print elements * }); 

试试这个jquery库,jQuery Print Element

http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/

这是一个JQuery和JavaScript解决方案来打印div样式(内部和外部CSS)

 $(document).ready(function() { $("#btnPrint").live("click", function () {//$btnPrint is button which will trigger print var divContents = $(".order_summery").html();//div which have to print var printWindow = window.open('', '', 'height=700,width=900'); printWindow.document.write(''); printWindow.document.write('');//external styles printWindow.document.write(''); printWindow.document.write(''); printWindow.document.write(divContents); printWindow.document.write(''); printWindow.document.close(); printWindow.onload=function(){ printWindow.focus(); printWindow.print(); printWindow.close(); } }); }); 

这将在新窗口中打印您的div。

用于触发事件的按钮

  

有一种方法可以将它与隐藏的div一起使用,但你必须使用printElement()函数和css进行更多的工作。

CSS:

 #SelectorToPrint{ display: none; } 

脚本:

  $("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}}) 

这将覆盖您打开的新窗口中的display:none,并且内容将显示在打印预览页面上,并且您站点上的div保持隐藏状态。

您可以按照以下步骤操作:

  1. 将要打印的div包装到另一个div中。
  2. 在css中将包装器div显示状态设置为none。
  3. 保持你想要打印显示状态为div的div,无论如何它将被隐藏,因为它的父隐藏。
  4. 只需调用$('SelectorToPrint').printElement();