我正在使用jQuery Cycle2和Carousel插件在我的网站上显示一些事件。一切都很好,但我希望可见的选项从平板电脑(768px和1030px之间)从5变为3,然后在手机(小于768px)上更改为1。所有其他选项都可以保持不变。此代码被黑客入侵并凌乱,所以我正在寻找一种更好的方法来做到这一点。另外,目前仅适用于刷新。很好,但是如果您调整大小时,它会实时重新加载并实时工作,那就太好了。这是我当前的代码:

// Events
var ww = document.body.clientWidth;
$(document).ready(function() {
    adjustEvents();
})
$(window).bind('resize orientationchange', function() {
    ww = document.body.clientWidth;
    adjustEvents();
});

var adjustEvents = function() {
    if (ww > 1030) {
        $('.cycle').cycle({
            fx:'carousel',
            swipe:true,
            timeout:5000,
            slides:'> article',
            carouselVisible:5,
            carouselFluid:true,
            autoHeight:'calc',
            prev:'#prev',
            next:'#next'
        });
    } 
    else if (ww >= 768) {
        $('.cycle').cycle({
            fx:'carousel',
            swipe:true,
            timeout:5000,
            slides:'> article',
            carouselVisible:3,
            carouselFluid:true,
            autoHeight:'calc',
            prev:'#prev',
            next:'#next'
        });
    }
    else if (ww < 768) {
        $('.cycle').cycle({
            fx:'carousel',
            swipe:true,
            timeout:5000,
            slides:'> article',
            carouselVisible:1,
            carouselFluid:true,
            autoHeight:'calc',
            prev:'#prev',
            next:'#next'
        });
    }
}
有帮助吗?

解决方案

$(document).ready(adjustEvents);
$(window).on('resize orientationchange', adjustEvents);

function adjustEvents() {
    var ww  = document.body.clientWidth,
        vis = ww > 1030 ? 5 : (ww >= 768 ? 3 : 1);
    $('.cycle').cycle({
        fx              : 'carousel',
        swipe           : true,
        timeout         : 5000,
        slides          : '> article',
        carouselVisible : vis,
        carouselFluid   : true,
        autoHeight      : 'calc',
        prev            : '#prev',
        next            : '#next'
    });
}

其他提示

这是代码的“修剪”版本...

// Events
var ww = document.body.clientWidth;
$(document).ready(function() {
    adjustEvents();
})
$(window).bind('resize orientationchange', function() {
    ww = document.body.clientWidth;
    adjustEvents();
});

var adjustEvents = function() {
    var options = {
        fx:'carousel',
        swipe:true,
        timeout:5000,
        slides:'> article',
        carouselFluid:true,
        autoHeight:'calc',
        prev:'#prev',
        next:'#next'
    }

    if (ww > 1030) {
        options.carouselVisible = 5;
    } 
    else if (ww >= 768) {
        options.carouselVisible = 3;
    }
    else if (ww < 768) {
        options.carouselVisible = 1;
    }
    $('.cycle').cycle(options);
}

我真正要做的就是创建一个将周期选项存储的变量,而仅更改与每个宽度相关的1个属性。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top