$(窗口).resize()和打印预览模式
我有一段非常简单的代码,可以在resize后刷新窗口。
$(window).resize(function() { location.reload(); });
当我尝试在Chrome中打开打印预览模式(Ctrl + P)时,它也会刷新它。 任何想法如何避免这种行为?
要确定打印操作,有两个事件: beforeprint
和afterprint
。 使用这些事件,可以在打印激活的onbeforeprint
中设置一些标志,并在resize
处理程序中检查此标志。
window.onbeforeprint = function() { print = true; };
很遗憾,Chrome 还不支持这些活动 。 可以使用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/ 。