Nic*_*ick 2 javascript printing iframe jquery
$('#my_button').on('click', function (e) {
var iframe = document.createElement('iframe');
iframe.id = "my_iframe";
iframe.onload = function() {
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.getElementsByTagName('body')[0].innerHTML = "<p>test123</p>";
iframe.contentWindow.focus();
iframe.contentWindow.print();
$("#my_iframe", top.document).remove();
};
document.getElementsByTagName('body')[0].appendChild(iframe);
});
Run Code Online (Sandbox Code Playgroud)
没有这remove条线,它打印得很好。但是,该remove行在iframe有机会执行print(). 如何设置某种回调,以便它打印然后才删除 iframe?
谢谢。
我在搜索打印事件检测时找到了这个解决方案:
http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
在这里,我按照 Stano 的要求添加了 JS 代码,但阅读整个链接帖子也很重要,因为这种方法存在局限性。一般来说,这篇文章是关于仅在 IE 中有效的 onafterprint 事件以及使该事件在其他浏览器中有效的解决方案。
(function() {
var beforePrint = function() {
console.log('Functionality to run before printing.');
};
var afterPrint = function() {
console.log('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4693 次 |
| 最近记录: |