我一直在使用下面的代码打印我的页面:
window.print();
下图是 Google chrome 浏览器中打印预览的样子。它有两个主要按钮:print
和 cancel
。
我想知道用户是否点击了print
或cancel
按钮。我所做的是使用 jquery:
打印预览的HTML代码:
<button class="print default" i18n-content="printButton">Print</button>
<button class="cancel" i18n-content="cancel">Cancel</button>
J查询代码:
$('button > .cancel').click(function (e) {
alert('Cancel');
});
$('button > .print').click(function (e) {
alert('Print');
});
我尝试了上面的代码,但没有成功。我错过了什么?
最佳答案
您无法直接从常规网页访问 Chrome 的内部窗口(在本例中为打印对话框)。
(function () {
var beforePrint = function () {
alert('Functionality to run before printing.');
};
var afterPrint = function () {
alert('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
//alert($(mediaQueryList).html());
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
或者,如果您想在打印预览打开时执行某些操作,您可以尝试以下操作:
$(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
setTimeout(function () { CallAfterWindowLoad();}, 5000);
return true;
}
});
function CallAfterWindowLoad()
{
alert("Open and call");
}
引用: How to capture the click event on the default print menu called by Javascript window.print()
也许如果您提供对这两个按钮单击事件的要求,我们可以为您提供替代解决方案。
关于javascript - 确定是否单击了 Google Chrome 打印预览中的打印/取消按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912933/