fullcalendar 根据屏幕宽度动态更改默认视图

fullcalendar dynamically change default view based on screen width

我正在使用 fullcalendar,下面的代码可以让我在使用 turbolinks 的同时呈现 fullcalendar。

function eventCalendar() {
  return $('#event_calendar').fullCalendar({
    defaultView: 'agendaWeek',
    header: {
        left: 'prev,today,next',
        center: 'title',
        right: 'agendaDay,agendaWeek'
    },    
  });
};
function clearCalendar() {
  $('#event_calendar').fullCalendar('delete'); // In case delete doesn't work.
  $('#event_calendar').html('');
};
$(document).on('turbolinks:load', eventCalendar);
$(document).on('turbolinks:before-cache', clearCalendar)

但是我想动态地 changeView defaultView 基于screenWidth。类似这样的东西,但由于某种原因它不起作用:

if (window.innerWidth < 800) {
            $('#event_calendar').fullCalendar('changeView', 'agendaDay');
        }

if(window.innerWidth < 800){
    $('#event_calendar').fullCalendar('changeView', 'agendaDay');
}else{
    $('#event_calendar').fullCalendar('changeView', 'agendaWeek');
}

如何使其适应我的日历?请帮忙!

如果 "dynamically change" 你的意思是你想在用户调整浏览器大小时更改它,那么你需要监听 window 调整大小。

$(window).resize(function() {
  if(window.innerWidth < 800){
    $('#event_calendar').fullCalendar('changeView', 'agendaDay');
  } else {
    $('#event_calendar').fullCalendar('changeView', 'agendaWeek');
  }
});

还要检查您的浏览器控制台是否有错误。从 4.0+ 版本开始,这些视图似乎已重命名 see changelog,因此您可能需要像这样传递不同的视图名称:

$(window).resize(function() {
  if(window.innerWidth < 800){
    $('#event_calendar').fullCalendar('changeView', 'timeGridDay');
  } else {
    $('#event_calendar').fullCalendar('changeView', 'timeGridWeek');
  }
});

如果有人对这里感兴趣,请了解如何使用 React/Typescript。

import React, { FunctionComponent } from 'react';
import FullCalendar, { ViewContentArg } from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';

const Calendar: FunctionComponent = (): JSX.Element => {
    const handleSize = (event: ViewContentArg): void => {
        let contentAPi = event.view.calendar;
        if (window.innerWidth < 800) {
            contentApi.changeView('timeGridDay');
        } else {
            contentApi.changeView('timeGridWeek');
        }
    }
    return <FullCalendar
        plugins={ [dayGridPlugin, timeGridPlugin, interactionPlugin] }
        windowResize={ handleSize }
    />
}