0

大家好,我正在尝试让我的滑块选择动态改变窗口的宽度并将正确的变量“newscount”放入“slidesPerSlide:window.newscount”并重新加载最后一部分:

swiperLoop = $('.swiper-loop').swiper({
    slidesPerSlide : window.newscount,
    loop:false
}); 

请帮助我,代码如下:

$(window).on('load', function(){

    $(window).on('resize', function() {
        var w = $(window).width();
        if (w < 321) {
            var newscount = "2";
        }
        else if (w < 480) {
            var newscount = "3";
        }
        else if (w < 640) {
            var newscount = "5";
        }
        else if (w < 720) {
            var newscount = "8";
        }
        else if (w > 721) {
            var newscount = "8";
        }
    }); 

    swiperLoop = $('.swiper-loop').swiper({
        slidesPerSlide : window.newscount,
        loop:false
    });

});
4

2 回答 2

1

您需要根据窗口大小初始化 swiper,然后更新事件的slidesPerSlide参数window.resize

$(function(){
    var width = $(window).width();

    var swiperLoop = $('.swiper-loop').swiper({
        slidesPerSlide: getSlideCount(width),
        loop: false
    });

    $(window).on('resize', function() {
        width = $(window).width();
        swiperLoop.params.slidesPerSlide = getSlideCount(width);
    }); 
});

function getSlideCount(windowSize) {
    if (windowSize < 321) {
        return 2;
    } else if (windowSize < 480) {
        return 3;
    } else if (windowSize < 640) {
        return 5;
    } else {
        return 8;
    }
}

此外,最好不要向window对象添加全局变量。这可能会导致其他库中的冲突或意外行为。

于 2013-06-06T15:13:39.513 回答
0

$(window).on('load', function(){

$(window).on('resize', function() {
    var w = $(window).width();

    this.newscount="0";

    if (w < 321) {
        this.newscount="1";
    }
    else if (w < 480) {
       this.newscount="2";
    }
    else if (w < 640) {
      this.newscount="3";
    }
    else if (w < 720) {
       this.newscount="4";
    }
    else if (w > 721) {
        this.newscount="5";
    }
}); 

swiperLoop = $('.swiper-loop').swiper({
    slidesPerSlide : this.newscount,
    loop:false
});

});

于 2013-06-06T15:15:03.587 回答