【发布时间】:2011-05-29 15:58:06
【问题描述】:
我在index.html 上有一个“打印”按钮。打印print.html 文件需要什么代码?我的意思是,当我按下index.html 的按钮时,打印页面print.html。
【问题讨论】:
-
无负载。我需要通过按钮打印外部文件。
标签: javascript html printing
我在index.html 上有一个“打印”按钮。打印print.html 文件需要什么代码?我的意思是,当我按下index.html 的按钮时,打印页面print.html。
【问题讨论】:
标签: javascript html printing
function closePrint () {
document.body.removeChild(this.__container__);
}
function setPrint () {
this.contentWindow.__container__ = this;
this.contentWindow.onbeforeunload = closePrint;
this.contentWindow.onafterprint = closePrint;
this.contentWindow.focus(); // Required for IE
this.contentWindow.print();
}
function printPage (sURL) {
var oHiddFrame = document.createElement("iframe");
oHiddFrame.onload = setPrint;
oHiddFrame.style.visibility = "hidden";
oHiddFrame.style.position = "fixed";
oHiddFrame.style.right = "0";
oHiddFrame.style.bottom = "0";
oHiddFrame.src = sURL;
document.body.appendChild(oHiddFrame);
}
然后使用
onclick="printPage('print_url');"
【讨论】:
我想你在找window.print()
更新
刚刚注意到您已经在其中指定了文件名,并且您希望在单击index.html 上的按钮时打印print.html。没有内置的方法可以做到这一点(从某种意义上说,您不能将任何参数传递给 window.print() 以指示要打印的文档)。您可以做的是将要打印的文档加载到 iframe 中或打开一个新窗口并在加载时调用该容器上的 window.print()。
这里有一些讨论同一件事的论坛帖子和网页:
更新 2
这里有一些简单粗暴的代码 - 请注意,这只有在您的两个页面都在同一个域中时才有效。此外,Firefox 似乎也会为空 iframe 触发 load 事件 - 因此打印对话框将在加载时立即显示,即使没有为 iframe 设置 src 值。
index.html
<html>
<head>
<title>Index</title>
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function(){
$('#loaderFrame').load(function(){
var w = (this.contentWindow || this.contentDocument.defaultView);
w.print();
});
$('#printerButton').click(function(){
$('#loaderFrame').attr('src', 'print.html');
});
});
</script>
<style>
#loaderFrame{
visibility: hidden;
height: 1px;
width: 1px;
}
</style>
</head>
<body>
<input type="button" id="printerButton" name="print" value="Print It" />
<iframe id="loaderFrame" ></iframe>
</body>
</html>
print.html
<html>
<head>
<title>To Print</title>
</head>
<body>
Lorem Ipsum - this is print.html
</body>
</html>
更新 3
你可能还想看看这个:How do I print an IFrame from javascript in Safari/Chrome
【讨论】:
src 的 iframe,它也会触发加载事件。你需要解决这个问题。如果这回答了您的问题,请告诉我。
您可以使用 JQuery printPage 插件 (https://github.com/posabsolute/jQuery-printPage-plugin)。这个插件很好用,你可以简单地打印一个外部 html 页面。
例子:
<html>
<head>
<title>Index</title>
<script src="http://www.position-absolute.com/creation/print/jquery.min.js" type="text/javascript"></script>
<script src="http://www.position-absolute.com/creation/print/jquery.printPage.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$(".btnPrint").printPage();
});
</script>
</head>
<body>
<input type="button" id="printerButton" name="print" value="Print It" />
<p><a class="btnPrint" href='iframe.html'>Print!</a></p>
</body>
</html>
【讨论】: