Printing
打印页面不需要 jQuery,只需要 JavaScript 函数:window.print();
.
如果需要打印特定内容,可以通过CSS隐藏其余内容(并格式化打印区域):
<style media="screen">
.noPrint{ display: block; }
.yesPrint{ display: block !important; }
</style>
<style media="print">
.noPrint{ display: none; }
.yesPrint{ display: block !important; }
</style>
如您所见,通过设置media样式标签的属性中,您可以为普通视图(屏幕)和打印视图(打印)设置样式。完整文章是here.
Dynamism
您可以为该过程添加一定的活力,但请记住,它可以动态地对于用户,但在您的代码中你必须找到并且event附上印刷品。该事件可能是锚点中的点击:
<a href='javascript:window.print();'>Print</a>
它可能是onload您页面的事件:
window.onload = function () {
window.print();
}
或者您可能需要注意的任何其他事件(请注意,现在我正在使用 jQuery):
var doPrintPage;
function printPage(){
window.print();
}
$(document).ready(function(){
$('input').blur(function(){
//3sec after the user leaves the input, printPage will fire
doPrintPage = setTimeout('printPage();', 3000);
});
$('input').focus(function(){
//But if another input gains focus printPage won't fire
clearTimeout(doPrintPage);
});
});
上面的代码非常简单:用户留下输入三秒后,打印页面会火。如果一个输入在这三秒内获得焦点,打印页面不会被调用。我真的不认为这个精确的代码是您所需要的,但我会指出如何模拟dynamism。这里可以看到设置超时时间 and 清除超时定义。
编辑:我几乎不建议你通过 CSS 隐藏不需要打印的 html,如上所述并调用窗口打印。不管怎样,我在这里添加了一些代码来通过新页面执行此操作。
从全新页面打印
如果您想打印from一个与您所显示的页面完全不同的页面,您可以请求该页面,在服务器端管理 html,然后告诉该页面在加载后立即打印。至少有两种方法可以做到这一点。让我们一步步看看它们:
A) 第一个选择是将 GridView 发送到新页面并从那里打印。问题是您无法轻松打开新页面来执行此操作,因此您必须从页面浏览到显示要打印的 html 的新页面。
A1) 为此,您需要用表单包围 GridView:
<form runat="server">
<asp:GridView id="gridView" />
<asp:Button id="btnPrint" Text="Print" runat="server" OnClick="btnPrint_Click" />
</form>
A2) 然后从 *btnPrint_Click* 您将调用您的“printPage.aspx”。请记住,如果您使用 JS/jQuery 更改了 GridView,这些更改可能不可用(因为 .NET 很可能读取隐藏状态变量而不是您的 GridView)。
B) 第二种方法是通过 JavaScript。但请记住,通过此选择,如果您想在新页面中编辑表格,您将遇到困难(因为您不会收到 GridView,而是收到 html)。好处是您可以轻松打开新页面:
B1)当然,您需要一个表单(注意它的目标和操作),例如:
<form id="myPageForm" name="myPageForm" target="_blank" action="printPage.aspx">
<input type="hidden" name="htmlToPrint" id="htmlToPrint" />
<input type="button" value="submit">Print</button>
</form>
B2) 然后你必须将数据传递到该锚点。在提交表单之前,请使用表数据设置输入:
$(document).ready(function(){
$('#myPageForm').submit(function(){
//Filling the hidden input
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
$("#htmlToPrint").value(htmlToPrint);
return true;
});
});
一旦您的服务器端 (printPage.asx) 有了数据,您就可以轻松创建要打印的 HTML 并在该页面上调用 window.print()onload, 如上所述。