如果有人有兴趣向 Flatpickr 添加年份下拉选择选项,这是我的解决方案
// plugin js file
/**
* Flatpickr Year Select Plugin.
* @author Labi Romabravo
*/
/**
*
* @returns {Function}
*/
const yearDropdownPlugin = function (pluginConfig) {
var defaultConfig = {
text: '',
theme: "light",
date: new Date(),
yearStart: 100,
yearEnd: 2,
};
var config = {};
for (var key in defaultConfig) {
config[key] = pluginConfig && pluginConfig[key] !== undefined ? pluginConfig[key] : defaultConfig[key];
}
var getYear = function (value) {
var date = value.split("/");
return parseInt(date[2], 10);
}
var currYear = new Date().getFullYear();
var selectedYear = getYear(config.date);
var yearDropdown = document.createElement("select");
var createSelectElement = function (year) {
var start = new Date().getFullYear() - config.yearStart;
var end = currYear + config.yearEnd;
for (var i = end; i >= start; i--) {
var option = document.createElement("option");
option.value = i;
option.text = i;
yearDropdown.appendChild(option);
}
yearDropdown.value = selectedYear;
};
return function (fp) {
fp.yearSelectContainer = fp._createElement(
"div",
"flatpickr-year-select " + config.theme + "Theme",
config.text
);
fp.yearSelectContainer.tabIndex = -1;
createSelectElement(selectedYear);
yearDropdown.addEventListener('change', function (evt) {
var year = evt.target.options[evt.target.selectedIndex].value;
fp.changeYear(year);
});
fp.yearSelectContainer.append(yearDropdown);
return {
onReady: function onReady() {
var name = fp.monthNav.className;
const yearInputCollection = fp.calendarContainer.getElementsByClassName(name);
const el = yearInputCollection[0];
el.parentNode.insertBefore(fp.yearSelectContainer, el.parentNode.firstChild);
}
};
};
}
export default yearDropdownPlugin
// if (typeof module !== "undefined")
// module.exports = yearDropdownPlugin;
用法
import yearDropdownPlugin from "@/utils/year_flatpickr_plugin";
var input = document.querySelector("#" + this.containerId);
this.datepicker = flatpickr(input, {
plugins: [
new yearDropdownPlugin({
date: this.value,
yearStart: this.yearStart,
yearEnd: this.yearEnd
})
],
wrap: true,
enableTime: false,
dateFormat: "d/m/Y",
minDate: this.min
//mode: "range"
});
CSS
.flatpickr-current-month .numInputWrapper {
display: none;
}
.flatpickr-current-month span.cur-month {
margin-right: 10px;
width: 85px;
font-size: 0.75em;
top: 0px;
padding-top: 10px;
padding-right: 2px;
position: absolute;
left: 0px;
font-weight: 600;
text-align: right;
}
.flatpickr-current-month {
width: 100px;
}
.flatpickr-year-select {
background-color:#052f66;
z-index: 100;
position: absolute;
top: 5px;
right: 70px;
width: 100px;
}
.flatpickr-year-select select{
width: 100%;
height: 24px;
font-weight: 600;
outline: 0;
overflow: hidden;
background: #ffffff;
color: #747a80;
border: #ffffff;
padding: 0;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 6px;
}
最终输出