我試圖打印iframe內容。在Opera和Chrome中打印iframe內容
contentWindow.focus();
contentWindow.print();
此代碼適用於IE,Firefox和Safari。但不要在Chrome和Opera中運行。這些瀏覽器打印整個頁面。
我試圖用這個主題How do I print an IFrame from javascript in Safari/Chrome。但它沒有幫助我。
有人可以幫助我嗎?
我試圖打印iframe內容。在Opera和Chrome中打印iframe內容
contentWindow.focus();
contentWindow.print();
此代碼適用於IE,Firefox和Safari。但不要在Chrome和Opera中運行。這些瀏覽器打印整個頁面。
我試圖用這個主題How do I print an IFrame from javascript in Safari/Chrome。但它沒有幫助我。
有人可以幫助我嗎?
這是Opera中的一個已知錯誤。除了尋求解決方法上面的想法,你可能想的是這樣玩:
var clone=document.documentElement.cloneNode(true)
var win=window.open('about:blank');
win.document.replaceChild(clone, win.document.documentElement);
win.print();
我沒有測試過這一點,但它應該在彈出窗口中創建的頁面的副本,並打印出來,而不必第二次從服務器加載內容或丟失可能需要打印的任何DOM修改。
據我所知,無法打開新窗口實現iframe打印是不可能的。
我的打印功能:
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) {
var href = contentWindow.location.href;
href = href.indexOf("?") > -1 ? href + "&print=1" : href + "?print=1";
var printWindow = window.open(href, "printWindow", "scrollbars=yes");
printWindow.focus();
}
else {
contentWindow.focus();
contentWindow.print();
}
而且我下面的代碼添加到身體(當打印== 1)結束:
<script type='text/javascript'>
function invokePrint() {
if (document.readyState && document.readyState!='complete')
setTimeout(function() { invokePrint(); }, 50);
else if (document.body && document.body.innerHTML=='false')
setTimeout(function() { invokePrint(); }, 50);
else {
focus();
print();
}
}
invokePrint();
</script>
我不能使用Chrome重現您的問題。但是,Opera試圖只打印iframe時確實仍然打印整個外部頁面。
我已經設計了一個解決方法,儘管它的確大部分工作,但它不是100%故障安全(其中包括Opera換行打印;我不知道如何在這種情況下計算正確的高度)。這就是說,下面的代碼至少合理(使用jQuery方便):
if ($.browser.opera) {
var ifr = $('#youriframe');
var ifrbody = ifr.get(0).contentDocument.body;
var sheet = $([
'<style type="text/css" media="print">',
'body * {',
' display: none;',
'}',
'#youriframe {',
' border: none;',
' display: block;',
' height: ', ifrbody.scrollHeight, 'px;',
' margin: 0px;',
' padding: 0px;',
' width: ', ifrbody.scrollWidth, 'px;',
'}',
'<\/style>'
].join(''));
$('head').append(sheet);
window.print();
sheet.remove();
}
希望這有助於。
我想上面的代碼,並在更改上面的代碼後,我帶着確鑿的代碼如下
var win=window.open('about:blank');
win.document.write('<html><head></head><body>');
win.document.write('<iframe frameBorder="0" align="center" src="'+window.location.href+'" onload="test()" style="width: 619px; height: 482px;"></iframe>');
win.document.write('<scr'+'ipt>function test(){window.focus();window.print()}</sc'+'ript></body></html>');
win.document.close();
if (window.focus) {win.focus()}
試試這個
從鏈接的文章好像至少爲Chrome,你應該有成功。 iframe是否位於不同的域上? – Paul
不是。它來自同一個域。 –