如何让FullCalendar自定义prev/next/today按钮自动调用locale翻译?
解决FullCalendar自定义按钮自动翻译失效的问题
核心思路
不要硬写自定义按钮的text属性,而是利用FullCalendar已加载的locales-all.js语言包,动态获取对应语言的翻译文本,实现和默认按钮一致的自动翻译效果。
具体实现方案
方案1:通过日历实例的localeData动态更新文本
利用日历的datesSet钩子,在日历加载或切换日期时,通过localeData()方法获取当前语言的翻译值,更新按钮文本:
document.addEventListener('DOMContentLoaded', function() { const calendarEl = document.getElementById('calendar'); const calendar = new FullCalendar.Calendar(calendarEl, { locale: 'auto', // 自动匹配浏览器语言 headerToolbar: { left: 'prev,today,next', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, customButtons: { next: { click: function() { calendar.next(); // 复用默认next按钮逻辑,也可自定义 } }, prev: { click: function() { calendar.prev(); // 复用默认prev按钮逻辑,也可自定义 } }, today: { click: function() { calendar.today(); // 复用默认today按钮逻辑,也可自定义 } } }, datesSet: function(info) { // 获取当前语言包的翻译数据 const localeData = info.view.calendar.localeData(); // 更新自定义按钮的文本 info.view.calendar.getCustomButton('next').textContent = localeData.next(); info.view.calendar.getCustomButton('prev').textContent = localeData.prev(); info.view.calendar.getCustomButton('today').textContent = localeData.today(); } }); calendar.render(); });
方案2:初始化时直接读取locale翻译对象
提前检测浏览器语言,从locales-all.js的全局FullCalendar.locales对象中提取对应翻译文本,初始化时直接赋值:
document.addEventListener('DOMContentLoaded', function() { // 自动检测浏览器语言,兼容不同格式(如zh-CN、zh) const browserLocale = navigator.language || navigator.userLanguage; const matchedLocale = FullCalendar.locales[browserLocale] || FullCalendar.locales[browserLocale.split('-')[0]] || FullCalendar.locales['en']; // 兜底用英文 const calendarEl = document.getElementById('calendar'); const calendar = new FullCalendar.Calendar(calendarEl, { locale: browserLocale, headerToolbar: { left: 'prev,today,next', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, customButtons: { next: { text: matchedLocale.buttonText.next, click: function() { calendar.next(); } }, prev: { text: matchedLocale.buttonText.prev, click: function() { calendar.prev(); } }, today: { text: matchedLocale.buttonText.today, click: function() { calendar.today(); } } } }); calendar.render(); });
关键注意事项
- 确保
locales-all.js在FullCalendar核心脚本之后引入,保证全局FullCalendar.locales对象可访问。 locale: 'auto'会自动匹配浏览器语言,无需手动指定;如果需要固定语言,直接传入对应locale代码(如'zh-cn')即可。- 自定义按钮的
click逻辑建议复用FullCalendar内置的prev()、next()、today()方法,保持和默认按钮一致的交互行为。
内容的提问来源于stack exchange,提问作者Chungyen Tsai
相关产品推荐
相关产品推荐

