使用Jquery窗口大小调整函数结果更新变量



我想在飞行中更新全局变量(窗口调整大小)。Body_size变量应该包含它下面函数的结果。我知道这个变量位于作用域之外,但是我不知道如何传递它。请帮助。请参见下面的代码片段。

$(document).ready(function() {
  var body_size; // this updates correctly
  var resizeTimer;
  function setContainerWidth() {
    body_size = $('.container').width();
  }
  $(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      setContainerWidth();
     
    }, 200);
  });
  setContainerWidth();
  console.log(body_size);
  var SlidesInView = 3; // this should update depending on result below :
  $(window).on('resize', function() {
    setContainerWidth(); // to check width on resize?
    if (body_size => 980) {
      SlidesInView = 4; // change SlidesInView above if condition is met.
    } else if (body_size <= 640) {
      SlidesInView = 1; //change SlidesInView above if condition is met.
    }
  });
  console.log(SlidesInView);
  }); // doc ready
.container{
  height:100vh;
  width:100vw;
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="container">
</div>

基本上top变量body_size应该在用户调整窗口大小时更新自己的值

变量body_size仅在窗口大小调整事件中被分配,并且在console.log执行时初始未定义。

我已经修改了它,在负载上分配。

$(document).ready(function() {
    var body_size; // this should hold the value of function below. This should get updates on window resize.
    var resizeTimer;
  
    function setContainerWidth() {
      body_size = $('.container').width(); 
    }
  
    $(window).resize(function() {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function() {
        setContainerWidth(); 
        console.log(body_size); //retrieves actual width.
      }, 200);
    });
  
    setContainerWidth();
    console.log(body_size); //retrieves undefined, which means that body_size at the top is not updating.
  }); // doc ready
.container{
  height:100vh;
  width:100vw;
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="container">
</div>

让我们澄清一下情况:

  1. body_size不是顶级的,因为它在$(document).ready(function() {/*...*/});里面。如果你想使它成为顶级的,从function中删除它,并在它外面声明。

  2. 您声明的body_size是您在事件中更新的相同变量,因为没有相同名称的变量遮蔽它,因此您认为它未更新并且与您在事件中使用的不同的假设是错误的。

  3. 输出错误值的console.logresize window之前执行,因为script在此之前执行。

为了确保您理解这些东西的工作方式,请尝试下面的脚本:

  var body_size; // this should hold the value of function below. This should get updates on window resize.
  $(document).ready(function() {
    var resizeTimer;
    $(window).resize(function() {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function() {
        body_size = $('.container').width(); 
      }, 200);
    });
  }); // doc ready

打开页面和开发工具。调整window的大小,然后将其粘贴到控制台:

console.log(body_size); //retrieves actual width.

瞧!Body_size已更新!

最新更新