How to test if the browser supports the native placeholder attribute?

后端 未结 4 490
囚心锁ツ
囚心锁ツ 2020-12-13 04:35

I\'m trying to write a simple placeholder jQuery plugin for a site of mine but of course I only want to fire the function if the native placeholder attribute isn\'t supporte

相关标签:
4条回答
  • 2020-12-13 04:42

    The placeholder property exists on INPUT DOM objects in all browsers regardless whether or not the placeholder attribute has been defined on the HTML INPUT element.

    The correct way is:

    var Modernizr = {};
    // Create the input element for various Web Forms feature tests.
    var inputElem = document.createElement('input'), attrs = {};    
    Modernizr.input = (function(props) {
        for(var i = 0, len = props.length; i < len; i++) {
            attrs[props[i]] = props[i] in inputElem;
        }
        return attrs;
    })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
    
    if(!Modernizr.input.placeholder) {
        // Do something.
    }
    
    0 讨论(0)
  • 2020-12-13 04:45

    Use the Modernizr library, which you can find here: http://www.modernizr.com/

    And then do this:

    if (Modernizr.input.placeholder) {
      // your placeholder text should already be visible!
    } else {
      // no placeholder support :(
      // fall back to a scripted solution
    }
    

    Modernizr is really handy for testing the browser's support for almost all HTML5 functionality.

    0 讨论(0)
  • 2020-12-13 04:45

    I like having such a simple class ...

    var Browser = {
      Can: {
        Placeholder: function () {
          return 'placeholder' in document.createElement('input'); 
        }
      }
    }
    

    ... so you can easily check if your browser supports the placeholder attribute.

    if (Browser.Can.Placeholder()) {
    
    }
    
    0 讨论(0)
  • 2020-12-13 04:56

    You can add to $.support quite easily by inserting this at the top of the Javascript you've written:

    jQuery.support.placeholder = (function(){
        var i = document.createElement('input');
        return 'placeholder' in i;
    })();
    

    You can then use either $.support.placeholder or jQuery.support.placeholder anywhere in your code.

    NB This code adapted from diveintohtml5, the link provided by hellvinz above.

    0 讨论(0)
提交回复
热议问题