我想动态更新全局变量(窗口大小)。 body_size变量应该包含它下面的函数的结果。我明白变量不在范围之内,但是我不知道如何将它传递出去。请帮忙。请参阅下面的代码片段。使用窗口调整大小的函数结果更新变量jquery
$(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>
基本上顶可变body_size应该用一个值,每当用户改变窗口更新自身。
这里没有什么意外的事,它实际上更新了你的变量。但是在'window.resize'里面只有当你调整窗口的大小时才会触发。 'console.log'在'document.ready'中,当它被记录时,事件还没有被触发。 –