How do I simulate placeholder functionality on input date field?

后端 未结 14 1439
生来不讨喜
生来不讨喜 2020-11-27 03:35

It\'s impossible to use placeholder on date fields but I really need it.

I want two date inputs with texts \"From\" and \"To\" on each one as placeholders.

14条回答
  •  一向
    一向 (楼主)
    2020-11-27 04:15

    The input[type="date"] DOMElement only takes the following value: YYYY-MM-DD, any other format or text with be skipped.

    Live Demo

    HTML

    
    
    

    Pure JavaScript

    window.onload = function () {
        /* Grab all elements with a placeholder attribute */
        var element = document.querySelectorAll('[placeholder]');
    
        /* Loop through each found elements */
        for (var i in element) {
            /* If the element is a DOMElement and has the nodeName "INPUT" */
            if (element[i].nodeType == 1 && element[i].nodeName == "INPUT") {
    
                /* We change the value of the element to its placeholder attr value */
                element[i].value = element[i].getAttribute('placeholder');
                /* We change its color to a light gray */
                element[i].style.color = "#777";
    
                /* When the input is selected/clicked on */
                element[i].onfocus = function (event) {
                    /* If the value within it is the placeholder, we clear it */
                    if (this.value == this.getAttribute('placeholder')) {
                        this.value = "";
                        /* Setting default text color */
                        this.style.color = "#000";
                    };
                };
    
                /* We the input is left */
                element[i].onblur = function (event) {
                    /* If the field is empty, we set its value to the placeholder */
                    if (this.value == "") {
                        this.value = this.getAttribute('placeholder');
                        this.style.color = "#777";
                    }
                };
            }
        }
    }
    

    Performance review

    In this exact case, with 2 input elements, Pure JavaScript is ~40% ± 10% faster.

    With 32 input elements, the difference remains the same (~43% ± 10% faster for Pure JS).

提交回复
热议问题