简体   繁体   中英

How to fix placeholder for Internet Explorer?

I want to have placeholders for both text and password input fields. I can do this in everything besides Internet Explorer. How can this be done? Maybe jquery? Specifically for passwords, i want the placeholder to say, "password." And once the input is clicked the text inside it will show up as password text. Thanks! :)

IE9+ are suppose to support placeholder but I find that this is not the case. There are a few ways to 'pretend' to have placeholder. I find the best way to have a placeholder look/feel on IE is to create a jquery function that adds a div behind the input boxes (having the input boxes transparent) with the text you want displayed. Then when typing or data present either A display:none the div or opaque the input box.

Other people put the text in the input fields but this can be a pain with validation and, as you have found, password fields.

something like:

// Check browser type so we don't mess with other browsers that do this right
if (BrowserDetect.browser === 'Explorer') {
    // Find all placeholders
    $('[placeholder]').each(function(_index, _this) {
        var $this = $(this);
        var id = this.id;
        var thisValue = $this.val();
        var value = $this.attr('placeholder');
        var $element = $('#' + id + '_ph');
        if ( $element.length === 0 ) {
            // Add placeholder if no input you want to add it even if value in case they remove value
            $this.attr('placeholder', '');
            // Add the div (make sure you style ie_placeholder_fix
            // class with correct positioning etc)
            $('<div id="' + id + '_ph" class="ie_placeholder_fix">' + value + '</div>').insertAfter($this);
        }
        //Maybe you want to hide if it has a value?
        if ( thisValue ) { $element.hide(); } else { $element.show(); }
        $this.blur(checkForInput);
    });
}

You will only need to check if they have a value whether to hide the div if a value is pre-populated (ie an editable form)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM