如何在CLNDR.js中实现控制栏显示相邻月份名称及年份?
Got it, let's tackle this CLNDR.js control bar tweak! Your goal is to replace the default "Prev" and "Next" buttons with the previous month/year and next month/year (in a short format like Dec 2016 and Feb 2018) alongside the current month/year. Here's how to make that happen:
Step 1: Add Custom Month Data in the beforeRender Hook
CLNDR.js provides a beforeRender callback that runs right before the calendar renders. We can use this to calculate and format the previous/next month details, then attach them to the calendar object so the template can access them.
Here's the updated initialization code:
$('.calendar').clndr({ // Keep your existing configuration (like events, daysOfWeek, etc.) beforeRender: function(clndr) { // Calculate previous month's date const prevMonthDate = new Date(clndr.currentYear, clndr.currentMonth - 1, 1); // Calculate next month's date const nextMonthDate = new Date(clndr.currentYear, clndr.currentMonth + 1, 1); // Format using CLNDR's built-in month abbreviations + full year clndr.prevMonthLabel = `${clndr.monthNamesShort[prevMonthDate.getMonth()]} ${prevMonthDate.getFullYear()}`; clndr.nextMonthLabel = `${clndr.monthNamesShort[nextMonthDate.getMonth()]} ${nextMonthDate.getFullYear()}`; }, // Point to your custom template (make sure this matches your template's ID) template: $('#calendar-template').html() });
Step 2: Update the Control Bar Template
Now modify your control bar template to use the new labels we created, while keeping the existing button classes (so the month-switching functionality still works):
<div class="clndr-controls"> <div class="clndr-control-button clndr-previous-button"> <span><%= prevMonthLabel %></span> </div> <div class="month"><%= month %> <%= year %></div> <div class="clndr-control-button clndr-next-button rightalign"> <span><%= nextMonthLabel %></span> </div> </div>
How This Works
- The
beforeRenderhook lets us tap into CLNDR's internal state (current year/month) to calculate adjacent months. TheDateobject automatically handles year rollover (e.g., if current month is January, the previous month will be December of the prior year). clndr.monthNamesShortis CLNDR's default array of 3-letter month abbreviations (["Jan", "Feb", ..., "Dec"]). If you need custom abbreviations, you can override this in the CLNDR config by adding amonthNamesShortproperty with your preferred values.- We keep the original button classes (
clndr-previous-buttonandclndr-next-button) so clicking the new labels still triggers CLNDR's built-in month navigation—no extra event listeners needed!
内容的提问来源于stack exchange,提问作者Deepak Kamat

