HTML5 “placeholder” support

前端 未结 5 1855
傲寒
傲寒 2020-12-18 21:44

How can I find out if the browser supports the HTML5 placeholder tag, so I can decide whether to hook my jQuery placeholder plugin or not.

5条回答
  •  既然无缘
    2020-12-18 22:13

    I borrowed from the answer above and made it so that it is backwards compatible with older modern browsers as well as IE --

    With the below code, make sure you have both a 'value' and 'placeholder' attribute set for the input fields. In my particular case I needed to support IE variants.

    Explanation -- If the browser supports placeholder the input value is removed. If not, the older browsers will ignore the placeholder attributes and the below js mimics the default placeholder behavior. This script will also ignore any auth tokens for CSRF (was getting an error where the auth token values were getting cleared in my forms causing a CSRF warning in my Rails apps).

    Another approach to simplify the script itself is to assign a class to each input you specifically want to utilize this script and update the true statement accordingly (though the below method is a bit more dry).

    var placeholderSupported = !!( 'placeholder' in document.createElement('input') );
    
    if (placeholderSupported === true){
        $('input:not([type="submit"], [name="authenticity_token"])').val('');
    } else{
        $('input')
          .focus(function() {
                if (this.value === this.defaultValue) {
                    this.value = '';
                }
          })
          .blur(function() {
                if (this.value === '') {
                    this.value = this.defaultValue;
                }
        });
    }
    

提交回复
热议问题