我有一段非常简单的代码,可以在调整大小后刷新窗口。
$(window).resize(function() {
location.reload();
});
当我尝试在Chrome中打开“打印预览模式”(Ctrl + P)时,它也会刷新它。任何想法如何避免这种行为?
答案 0 :(得分:4)
要确定打印操作,有两个事件:beforeprint
和afterprint
。使用这些事件,可以在onbeforeprint
中设置一些标记,激活打印并在resize
处理程序中检查此标记。
window.onbeforeprint = function() {
print = true;
};
不幸的是Chrome doesn't support these events yet。可以使用Chrome matchMedia
中的解决方法:
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
console.log('onbeforeprint equivalent');
} else {
console.log('onafterprint equivalent');
}
});
Chrome的解决方案可能是这样的:
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
标记以允许进一步调整窗口大小。
有关此方法的更多信息 - http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/。