如何知道屏幕是减少还是增加? [即时的]

时间:2016-11-01 22:50:27

标签: javascript jquery

我正在尝试检查用户减少增加屏幕。

我有以下功能并且工作正常,但它仅依赖于初始屏幕尺寸

var width = $(window).width();

$(function(){

    $(window).resize(function(){

      var resizeWidth = $(this).width();

      if (resizeWidth > width) {

        console.log('increased!')
        width = width + 1;

      } else {

        console.log('reduced!')
        width = width - 1;

      }
    });
});

是否可以随时了解屏幕增加减少而不是初始屏幕尺寸?

谢谢大家!

2 个答案:

答案 0 :(得分:1)

您可以使用此代码检查增加和减少窗口宽度

var windowWidth = 0;

$(window).ready(function () {
  windowWidth = $(window).width();
})

$(window).resize(function () {
  var newWindowWidth = $(window).width();
  if (windowWidth >= newWindowWidth) {
    console.log('Decrease width');
  } else {
    console.log('Increase width');
  }
  
  windowWidth = newWindowWidth;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

您设置的window.resize将持续触发。只需在每次调整大小时存储旧宽度,并将其与新宽度进行比较,在比较后用新宽度替换旧宽度。

var win = $(window); // cache the window query since we'll be using it a lot

// set initial values
var oldWindowWidth = win.width();

// each time we resize
win.on('resize', function() {
  // get the new width
  var newWindowWidth = win.width();

  // compare it to the old width
  if (newWindowWidth > oldWindowWidth) {
    console.log('increased');
  }
  else if (newWindowWidth < oldWindowWidth) {
    console.log('descreased');
  }

  // update the old width
  var oldWindowWidth = newWindowWidth;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>