1

に基づいて変数に値を割り当てるelse..ifステートメントがあります。window.width私がやりたいのは、この値を内部で使用することですがwindow.resize、現時点では値を取得'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

このように再定義currentSizeしないでくださいvar

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 に答える