Bootstrap

js 监听页面缩放

js 监听页面缩放,主要用在浏览器发生页面缩放时,对页面布局进行调整,比如网站飘窗,通过js监听页面缩放调整飘窗位置。

  • 创建onzoom函数
// detect resize
(function() {
  var oldresize = window.onresize;
  window.onresize = function(e) {
    var event = window.event || e;
    if(typeof(oldresize) === 'function' && !oldresize.call(window, event)) {
      return false;
    }
    if(typeof(window.onzoom) === 'function') {
      return window.onzoom.call(window, event);
    }
  }
})();
  • 获取页面缩放比例
function detectZoom() {
  var ratio = 0,
      screen = window.screen,
      ua = navigator.userAgent.toLowerCase();

  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio;
  }
  else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
  }
  else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
    ratio = window.outerWidth / window.innerWidth;
  }

  if (ratio) {
    ratio = Math.round(ratio * 100);
  }
  return ratio;
}
  • 具体业务代码
setTimeout(function () {
  if (detectZoom() >= 125) {
    $('.piaochuang').css('left', '0px');
  } else {
    $('.piaochuan').css('left', '8%');
  }
}, 1000)

window.onzoom = function(e) {
  // zoom even
  if (detectZoom() >= 125) {
    $('.piaochuang').css('left', '0px');
  } else {
    $('.piaochuan').css('left', '8%');
  }
};

最后安利下自己的小程序,一款程序员刷题小程序。

在这里插入图片描述

;