How to add jQuery if statement inside a set of plugin options?

删除回忆录丶 提交于 2019-12-08 18:40:29

You can create the common settings object and then add other variables to it based on your conditions. Something like this:

var calendar = {
    timeFormat:'h(:mm)a',
    header:{
        left:'prev',
        center:'title',
        right:'next'
    },
    height: 650,
    titleFormat: {
        week: 'MMMM YYYY'
    },
    columnFormat: {
        week: 'dddd M/D',
        day: 'ddd M/D'
    }
};

if ($(window).width() <= 481){
    calendar.views = {
        basicThreeDay: {
            type: 'basic',
            duration: {
                days: 3
            },
            buttonText: '3 day'
        }
    };
    calendar.defaultView = 'basicThreeDay',
} else {
    calendar.defaultView = 'basicWeek',
}

$('#calendar').fullCalendar(calendar);

you can create a "view" var and set the "basicThreeDay" or "basicWeek" on document ready like this

var view="basicWeek";//default to basicWeek
if ($(window).width() <= 481){//for mobile
    view='basicThreeDay';
}
$('#calendar').fullCalendar({
    timeFormat:'h(:mm)a',
    header:{
        left:'prev',
        center:'title',
        right:'next'
    },
    height: 650,
    views: {
        basicThreeDay: {
            type: 'basic',
            duration: { days: 3 },
            buttonText: '3 day'
        },
    },
    defaultView:  view,//will be "basicWeek" on (width>481) and "basicThreeDay" for (width<=481)
    titleFormat: {
        week: 'MMMM YYYY'
    },
    columnFormat: {
        week: 'dddd M/D',
        day: 'ddd M/D'
    }
});    

or you can create a function in defaultView with your if statement and return the right string like this

$('#calendar').fullCalendar({
    timeFormat:'h(:mm)a',
    header:{
        left:'prev',
        center:'title',
        right:'next'
    },
    height: 650,
    views: {
        basicThreeDay: {
            type: 'basic',
            duration: { days: 3 },
            buttonText: '3 day'
        },
    },
    defaultView: function(){
        if ($(window).width() <= 481){
             return 'basicThreeDay';
        } else {
            return 'basicWeek';
        }
    }(),//you need to call the function  
    titleFormat: {
        week: 'MMMM YYYY'
    },
    columnFormat: {
        week: 'dddd M/D',
        day: 'ddd M/D'
    }
});    

if you set the "basicThreeDay" view regardless of the window width you can change between views like this

$(window).resize(function(){
    if ($(window).width() <= 481){
        $('#calendar').fullCalendar( 'changeView', 'basicThreeDay' );
    }
    else{
        $('#calendar').fullCalendar( 'changeView', 'basicWeek' );
    }
});

https://jsfiddle.net/f28ojwx9/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!