我有一个else..if语句,根据window.width
为变量赋值,我想要做的是在window.resize
中使用这个值,但此刻得到'undefined'
currentSize
的值//Code ran onload
if(windowWidth >= 924) {
incrementValue = 3;
currentSize = 'desktop';
}
else if(windowWidth > 615 && windowWidth < 924) {
incrementValue = 2;
currentSize = 'tablet';
}
else {
incrementValue = 1;
currentSize = 'mobile';
}
$(window).resize(function() {
windowWidth = $(window).width();
if(windowWidth >= 924) {
incrementValue = 3;
var newSize = 'desktop';
}
else if(windowWidth > 615 && windowWidth < 924) {
incrementValue = 2;
var newSize = 'tablet';
}
else {
incrementValue = 1;
var newSize = 'mobile';
}
console.log(currentSize); //'undefined'
if (currentSize !== newSize) {
var currentSize = newSize;
incrementTotal = 0;
slideIndex = 0;
//Reset slider to start
$carouselSlides.css( 'left', 0 );
}
});
。我应该怎么做以获得价值?
JS
{{1}}
答案 0 :(得分:3)
请勿使用currentSize
这样重新定义var
if (currentSize !== newSize) {
var currentSize = newSize;
删除var
if (currentSize !== newSize) {
currentSize = newSize;
以下示例允许您根据var
的存在重现或消除错误:
答案 1 :(得分:1)
<script>
//global scope
var currentSize = 'desktop', incrementTotal = 0, incrementValue = 0, slideIndex = 0, $carouselSlides = $('#carouselSlides');
function windowResize(windowWidth) {
var data = [];
if (windowWidth >= 924) {
data = ['desktop', 3];
} else if (windowWidth > 615 && windowWidth < 924) {
data = ['tablet', 2];
} else {
data = ['mobile', 1];
}
return data.length ? data : false;
}
$(window).resize(function() {
var windowWidth = $(this).width();
var data = windowResize(windowWidth);
// data[0] = desktop, tablet OR mobile
// data[1] = 1, 2 OR 3
incrementValue = data[1];
if (currentSize !== data[0]) {
currentSize = data[0];
incrementTotal = 0;
slideIndex = 0;
//Reset slider to start
$carouselSlides.css('left', 0);
}
// set the style for the current screen size
});
</script>
答案 2 :(得分:0)
你的newSize超出了范围:
$(window).resize(function() {
windowWidth = $(window).width();
var newSize =0;
if(windowWidth >= 924){
incrementValue = 3;
newSize = 'desktop';
} else if(windowWidth > 615 && windowWidth < 924) {
incrementValue = 2;
newSize = 'tablet';
} else {
incrementValue = 1;
newSize = 'mobile';
}
if (currentSize !== newSize) {
var currentSize = newSize;
incrementTotal = 0;
slideIndex = 0;
//Reset slider to start
$carouselSlides.css( 'left', 0 );
}
});