1

我正在使用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方法可以防止任何点击导致任何操作。然而,当我在单击下拉菜单时添加控制台语句时,它会出现在控制台上。

所以我的问题是如何在点击它时打开下拉菜单。请在此处找到该问题的示例。

4

3 回答 3

3

在我们的客户要求将年份选择器更改为更舒适的东西后来到这里。感谢上面提供一些指向 flatpickr 插件选项的链接的人。

如果有人仍然需要,这是我的解决方案。首先,我们在 html 页面中有一个设置脚本(后来称为 using 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>

我所做的只是添加了一些额外的代码,以便插入选择标记而不是现有元素,并提供事件处理,以便跟踪自定义选择中的值更改并将其传递给本机元素。在 orReady 事件中,原生年份选择器被隐藏,创建选择元素并实现 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>
于 2019-10-25T13:39:16.363 回答
2

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

最终输出 下拉预览

于 2019-05-24T19:01:16.410 回答
0

如果您查看源代码,flatpickr 正在将事件绑定到它自己的事件处理程序。 事件绑定位置的屏幕截图

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

于 2019-03-05T07:51:06.933 回答