基于宽度的动态重载函数

时间:2013-06-06 14:58:54

标签: jquery

大家好我想让我的滑块选择动态改变窗口的宽度,并将正确的变量“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
    });

});

2 个答案:

答案 0 :(得分: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对象。这可能会导致其他库中的冲突或意外行为。

答案 1 :(得分: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
});

});