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

时间:2015-03-27 09:00:39

标签: javascript jquery google-chrome browser

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

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

当我尝试在Chrome中打开“打印预览模式”(Ctrl + P)时,它也会刷新它。任何想法如何避免这种行为?

1 个答案:

答案 0 :(得分:4)

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

相关问题