使用jquery自动打印

前端之家收集整理的这篇文章主要介绍了使用jquery自动打印前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下格式的数据:

(虚拟条目)(id = posGridView)

当我处理销售时,一张小收据会自动打印所选列,而不是所有列.

由于此网格视图中的所有数据都可用,如何使用jquery以任何格式动态打印它?

编辑

实际上我想从上面的网格视图中动态打印这种格式

解决方法

印花

打印页面不需要jQuery,只需要JavaScript函数:window.print();.

如果需要打印特定内容,可以通过CSS隐藏其余内容(并格式化打印区域):

  1. <style media="screen">
  2. .noPrint{ display: block; }
  3. .yesPrint{ display: block !important; }
  4. </style>
  5. <style media="print">
  6. .noPrint{ display: none; }
  7. .yesPrint{ display: block !important; }
  8. </style>

如您所见,通过设置样式标记的media属性,您可以为普通视图(屏幕)和打印视图(打印)设置样式.全文是here.

力度

您可以为流程添加一定的动态,但请记住,它可以为用户提供动态,但在您的代码中,您必须找到并附加打印事件.该事件可能是锚点击:

< a href ='javascript:window.print();'>打印< / a>

它可能是您网页的onload事件:

  1. window.onload = function () {
  2. window.print();
  3. }

或者您可能需要注意的任何其他事件(请注意,现在我正在使用jQuery):

  1. var doPrintPage;
  2.  
  3. function printPage(){
  4. window.print();
  5. }
  6.  
  7. $(document).ready(function(){
  8. $('input').blur(function(){
  9. //3sec after the user leaves the input,printPage will fire
  10. doPrintPage = setTimeout('printPage();',3000);
  11. });
  12. $('input').focus(function(){
  13. //But if another input gains focus printPage won't fire
  14. clearTimeout(doPrintPage);
  15. });
  16. });

上面的代码非常简单:在用户离开输入三秒后,printPage将会触发.如果输入在这三秒内获得焦点,则不会调用printPage.我真的不认为这个精确的代码是你需要的,但我会指出如何模仿动态.这里可以看到setTimeoutclearTimeout的定义.

编辑:我几乎不建议你通过CSS隐藏你不想要的打印html,如上所述,并调用window.print.无论如何,我在这里添加了一些代码,用于通过新页面进行操作.

从全新页面打印

如果你想从一个完全不同的页面打印你正在展示的页面,你可以要求该页面,管理服务器端的html,然后在加载后立即告诉页面打印.至少有两种方法可以做到这一点.让我们一步一步看到它们:

A)第一种选择是将GridView发送到新页面并从那里打印.问题是您无法轻松打开新页面来执行此操作,因此您必须从页面浏览到显示html-to-print的新页面.

A1)为此,您需要使用以下形式包围GridView:

  1. <form runat="server">
  2. <asp:GridView id="gridView" />
  3. <asp:Button id="btnPrint" Text="Print" runat="server" OnClick="btnPrint_Click" />
  4. </form>

A2)然后从* btnPrint_Click *你将调用你的“printPage.aspx”.请记住,如果您使用JS / jQuery更改了GridView,那些更改可能无法使用(因为.NET可能会读取隐藏的状态变量而不是GridView).

B)第二种方法是通过JavaScript.但请记住,如果您想在新页面中编辑表格,那么通过此选择将会很困难(因为您将不会收到GridView,您将收到html).好消息是您可以轻松打开新页面

B1)当然,你需要一个表格(注意其目标和行动),例如:

  1. <form id="myPageForm" name="myPageForm" target="_blank" action="printPage.aspx">
  2. <input type="hidden" name="htmlToPrint" id="htmlToPrint" />
  3. <input type="button" value="submit">Print</button>
  4. </form>

B2)然后你必须将你的数据传递给那个锚点.在提交表单之前,使用表数据设置输入:

  1. $(document).ready(function(){
  2. $('#myPageForm').submit(function(){
  3. //Filling the hidden input
  4. var htmlToPrint = $(".posGridView").html(); //I'm using a class and not an ID 'cause .NET will change your GridView's ID when rendering you page
  5. $("#htmlToPrint").value(htmlToPrint);
  6. return true;
  7. });
  8. });

一旦在服务器端获得了数据(printPage.asx),就可以轻松地创建HTML-to-print并在该页面onload上调用window.print(),如上所述.

猜你在找的jQuery相关文章