1

我有一个 else..if 语句,它根据 为变量赋值window.width,我想做的是在 a 中使用这个值,window.resize但现在 get'undefined'获取currentSize该值。我应该怎么做才能获得价值?

JS

//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 );
    }
});
4

3 回答 3

3

不要currentSizevar这样重新定义

if (currentSize !== newSize) {
    var currentSize = newSize;

去除那个var

if (currentSize !== newSize) {
    currentSize = newSize;

这是一个示例,它允许您根据是否存在重现或消除错误var

于 2012-11-29T12:17:10.733 回答
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>
于 2012-11-29T12:47:00.900 回答
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 );
    }
  });
于 2012-11-29T12:26:07.733 回答