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

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

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

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

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

要确定打印操作,有两个事件:beforeprintafterprint。使用这些事件,可以在 onbeforeprint 中设置一些标志,打印激活并在 resize 处理程序中检查这个标志。

window.onbeforeprint = function() {
    print = true;
};

不幸的是Chromedoesn'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 中重置以允许进一步 window 调整大小。

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