问题描述
I have a very simple piece of code that refreshes window after resize.
$(window).resize(function() {
location.reload();
});
当我尝试在Chrome中打开打印预览模式(Ctrl + P)时,它也会刷新它。任何想法如何避免这种行为?
When I try to open Print Preview Mode (Ctrl + P) in Chrome, it refreshes it as well. Any ideas how to avoid that behavior?
推荐答案
确定打印操作有两个事件: beforeprint
和 afterprint
。使用这些事件,可以在 onbeforeprint
中设置一些激活打印的标志,并在 resize
处理程序中检查该标志。
To determine print actions there are two events: beforeprint
and afterprint
. Using these event it's possible to set some flag in onbeforeprint
that print activated and check this flag in resize
handler.
window.onbeforeprint = function() {
print = true;
};
不幸的是Chrome 。可以使用Chrome matchMedia
中的解决方法:
Unfortunately Chrome doesn't support these events yet. As workaround in Chrome matchMedia
may be used:
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
console.log('onbeforeprint equivalent');
} else {
console.log('onafterprint equivalent');
}
});
因此Chrome的解决方案可能如下所示:
So solution for Chrome might be like this:
var print = false;
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
print = true;
}
});
$(window).resize(function(event) {
if (!print) {
location.reload();
}
});
此后 print
标志应该重置 onafterprint
以允许进一步调整窗口大小。
After this print
flag should be reset in onafterprint
to allow further window resizes.
有关此方法的更多信息 - 。
More info about this approach - http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/.
这篇关于$(窗口).resize()和打印预览模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!