Flatpickr:添加下拉菜单以更改年份

时间:2018-07-19 14:19:44

标签: jquery flatpickr

我正在使用Flatpickr满足我的日历需求。它提供带有箭头的输入字段,用于更改年份。

我需要在日历中有一个下拉菜单,以便我可以从该下拉菜单中选择年份,然后日历指向该年份。

我为日历元素动态地赋予了一个特殊的类.birthDate。我已经向日历中动态添加了一个下拉菜单,如下所示:

var currYear = new Date().getFullYear()

var yearOptions = "";

for(var i =  1960; i <= currYear; i++) {
    var option = "<option value = " +  i + ">" + i + "</option>";
    yearOptions += option;
}

var yearDropdown = "<select class=\"year-dropdown\">" + yearOptions + "</select>";
 $(".birthDate .flatpickr-current-month").append(yearDropdown);

问题是,当我单击它时什么也没有发生。我的猜测是有一种preventDefault方法可以防止任何点击导致任何操作。但是,当我单击下拉菜单添加控制台语句时,它会出现在控制台上。

所以我的问题是如何单击它打开下拉列表。请找到问题here的示例。

3 个答案:

答案 0 :(得分:1)

应客户要求将“年选择器”更改为更舒适的方式后,请转到此处。感谢上面的人提供了一些Flatpickr插件选项的链接。

如果有人仍然需要它,这是我的解决方案。 首先,我们在html页面中有一个设置脚本(后来称为wicket)。它创建一个flatpickr实例并将其绑定到html元素:

<script type="text/javascript">
        const FLATPICKR_CUSTOM_YEAR_SELECT = 'flatpickr-custom-year-select';
        const initDatePicker = function (inputId) {
            $("#" + inputId).flatpickr({
                dateFormat: "d/m/Y",
                minDate: "01.01.1900",
                maxDate: "01.01.2100",
                allowInput: true,
                onChange: function () {
                    $("#" + inputId).blur();
                }
            })
        };
</script>

我所做的只是添加了一些其他代码,以便插入一个select标记而不是现有元素,并提供事件处理,以跟随自定义select中的值更改并将其传递给本机元素。 在orReady事件中,本机年份选择器被隐藏,创建select元素,并实现onChange事件,其中将所选值传递到本机年份元素。单击侧面箭头(更改月份)时,需要onMonthChange来更改年份值。 所以现在看起来像这样:

<script type="text/javascript">
        const FLATPICKR_CUSTOM_YEAR_SELECT = 'flatpickr-custom-year-select';
        const initDatePicker = function (inputId) {
            $("#" + inputId).flatpickr({
                dateFormat: "d/m/Y",
                minDate: "01.01.1900",
                maxDate: "01.01.2100",
                allowInput: true,
                onChange: function () {
                    $("#" + inputId).blur();
                },
               //here what was added
                onReady: function (selectedDates, dateStr, instance) {
                    const flatpickrYearElement = instance.currentYearElement;

                    const children = flatpickrYearElement.parentElement.children;
                    for (let i in children) {
                        if (children.hasOwnProperty(i)) {
                            children[i].style.display = 'none';
                        }
                    }

                    const yearSelect = document.createElement('select');
                    const minYear = new Date(instance.config._minDate).getFullYear();
                    const maxYear = new Date(instance.config._maxDate).getFullYear();
                    for (let i = minYear; i < maxYear; i++) {
                        const option = document.createElement('option');
                        option.value = '' + i;
                        option.text = '' + i;
                        yearSelect.appendChild(option);
                    }
                    yearSelect.addEventListener('change', function (event) {
                        flatpickrYearElement.value = event.target['value'];
                        instance.currentYear = parseInt(event.target['value']);
                        instance.redraw();
                    });

                    yearSelect.className = 'flatpickr-monthDropdown-months';
                    yearSelect.id = FLATPICKR_CUSTOM_YEAR_SELECT;
                    yearSelect.value = instance.currentYearElement.value;

                    flatpickrYearElement.parentElement.appendChild(yearSelect);
                },
                onMonthChange: function (selectedDates, dateStr, instance) {
                    document.getElementById(FLATPICKR_CUSTOM_YEAR_SELECT).value = '' + instance.currentYear;
                }
            })
        };
    </script>

答案 1 :(得分:0)

如果您查看源代码,flatpickr会将事件绑定到其自己的事件处理程序。 Screenshot of where the events are bound

点击实际上是在 documentClick 函数中处理的,我想这就是下拉菜单无法打开的原因。 另外,要创建下拉年份选择,请尝试编写Flatpickr插件(选中https://flatpickr.js.org/plugins/)。 还有一个封闭的票证,该票证是作为请求提出的(https://github.com/flatpickr/flatpickr/issues/965)。您可以对其进行检查和跟进。

答案 2 :(得分:0)

如果有人有兴趣向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;
}

最终输出 dropdown preview