问题描述
|
我在
index.html
上有一个“打印”按钮。打印print.html
文件需要什么代码?我的意思是,当我从index.html
按下按钮时,打印页面print.html
。
解决方法
我想您正在寻找
window.print()
更新资料
只是注意到您已经在其中指定了文件名,并且您想在单击index.html
上的按钮时打印print.html
。没有内置的方法可以执行此操作(从某种意义上说,您不能将任何参数传递给window.print()
来指示要打印的文档)。您可以做的是加载文档以将其打印到iframe或打开一个新窗口,并在加载时在该容器上调用ѭ4。
以下是一些讨论同一主题的论坛帖子和网页:
http://www.highdots.com/forums/javascript/printing-another-web-file-present-274201.html
http://www.webmasterworld.com/javascript/3524974.htm
http://www.felgall.com/jstip29.htm
更新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
您可能还想看一下:如何从Safari / Chrome中的javascript打印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>
, 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\');\"