window.devicePixelRatio change listener

前端 未结 1 2042
陌清茗
陌清茗 2021-02-15 07:13

window.devicePixelRatio will return 1 or 2 depending on if I\'m using my retina monitor or standard. If I drag the window between the two monitors, this property will change. Is

1条回答
  •  孤独总比滥情好
    2021-02-15 08:02

    You can listen to a media query with matchMedia that will tell you when the devicePixelRatio goes past a certain barrier (unfortunately not for arbitrary scale changes).

    e.g:

    window.matchMedia('screen and (min-resolution: 2dppx)').
        addListener(function(e) {
          if (e.matches) {
            /* devicePixelRatio >= 2 */
          } else {
            /* devicePixelRatio < 2 */
          }
        });
    

    The listener will be called when you drag a window between monitors, and when plugging in or unplugging an external non-retina monitor (if it causes the window to move from a retina to non-retina screen or vice-versa).

    window.matchMedia is supported in IE10+, and all other modern browsers.

    References: https://code.google.com/p/chromium/issues/detail?id=123694, MDN on min-resolution

    0 讨论(0)
提交回复
热议问题