以下是在Windows XP上的IE 8中一直运行良好的javascript代码.
<script type="text/javascript">
function printFrame(frameId) {
var iframe = $('#'+frameId)[0];
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
</script
Run Code Online (Sandbox Code Playgroud)
调用上述函数,然后在父页面中单击"打印框架"按钮.
<iframe id="testFrame" src="" name="testFrame"> </iframe>
<input type="button" onclick="printFrame('testFrame')" value="Print Frame"/>
Run Code Online (Sandbox Code Playgroud)
最近,我将我的机器升级到Windows 7,将IE 8升级到IE 11.
现在,这个相同的功能没有给出打印iframe内容的预期结果.我在chrome v34,firefox 30中进行了测试.除了在IE 11中,它似乎适用于它们.
在研究中,我发现iframe src是动态设置的,iframe.contentWindow不会返回例外的iframe窗口对象.
我尝试在iframe的jsp中使用window.print().如果src没有动态更改,这似乎有效.但是我需要根据父页面中另一个下拉框中的选择来更改iframe的内容.
例如,请检查IE 11中的以下链接.
http://plungjan.name/SO/testprintiframe.html
Run Code Online (Sandbox Code Playgroud)
链接第一次在iframe上打印内容.然后,单击按钮.这导致父窗口被发送到打印机而不是iframe内容.
然后我尝试了另一种方法.在iframe内容jsp中写下面的代码并尝试从父页面访问它.我无法访问该方法本身."iframe jsp中的脚本代码"
<script type="text/javascript">
function printFrame() {
window.print();
}
</script
Run Code Online (Sandbox Code Playgroud)
"父jsp中的脚本代码"
试试1:
<script type="text/javascript">
function printMyFrame(frameId) {
var iframe = $('#'+frameId)[0];
$(iframe).contents().printFrame();
}
</script
Run Code Online (Sandbox Code Playgroud)
试试2:
<script type="text/javascript">
function printMyFrame(frameId) {
setTimeout(function() {
window.frames[frameId].contentWindow.printFrame();
}, 200);
}
</script>
Run Code Online (Sandbox Code Playgroud)
我搜索并实现了谷歌搜索中找到的几乎所有方法来访问iframe窗口而不是父窗口.但是无法使用IE …
此解决方案在Firefox 3.0+中运行良好,但IE8/7只是打印整个页面,而不是特定的iframe.
这是单击打印链接时调用的函数:
var printfunc= function(){
var url = http://someurl.aspx;
//This iFrame has style="visibility: hidden; position: absolute; left: -9000px;"
var printIFrame = GetObj('PrintIFrame');
printIFrame.src = url;
}
Run Code Online (Sandbox Code Playgroud)
加载到隐藏iframe中的aspx调用onload事件处理程序上的print函数:
<body onload="PrintJS.Print();">
Run Code Online (Sandbox Code Playgroud)
打印功能:
this.Print = function(){
self.focus();
self.print();
return false;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试用"窗口"代替"自我".两种解决方案在FF中运行良好,但IE似乎没有得到正确的范围.有什么想法吗?跨浏览器解决方案会很棒!另外,我宁愿使用CSS打印样式,但我打印的内容与页面上的内容不同,因此需要将html加载到隐藏的iframe中.