$(window).resize()和打印预览模式

$(window).resize() and Print Preview Mode

本文关键字:模式 打印 resize window      更新时间:2023-09-26

我有一段非常简单的代码,可以在调整大小后刷新窗口。

$(window).resize(function() {
    location.reload();
});

当我尝试在Chrome中打开打印预览模式(Ctrl+p)时,它也会刷新它。有什么办法避免这种行为吗?

要确定打印操作,有两个事件:beforeprintafterprint。使用这些事件,可以在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();
  }
});

在此之后,应在onafterprint中重置print标志以允许进一步调整窗口大小。

有关此方法的更多信息-http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/.