グローバル変数をオンザフライで更新したい(ウィンドウのサイズ変更)。 body_size変数には、その下にある関数の結果が含まれているはずです。変数が範囲外にあることを理解していますが、どのように渡すかわかりません。助けてください。下記のスニペットをご覧ください。関数の結果を使用して変数を更新するwindow resize 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'の内部では' window'のサイズを変更したときにのみトリガされます。 'console.log'は' document.ready'にあり、ログに記録されるまでに 'event'はまだトリガされていません。 –