how to use HTML5 placeholder attribute with backward-compatibility in mind?

允我心安 提交于 2019-11-29 06:55:30

You can detect if a browser supports the attribute:

http://diveintohtml5.info/detect.html#input-placeholder

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

If it does, do nothing. If it doesn't, you can use JS to grab the placeholder value and then insert it into the field as you see fit (perhaps as default value) and then add the appropriate interactions to simulate the HTML5 placeholder behaviors.

rolling stone

@marcgg wrote a great JQuery placeholder plugin that basically replicates the placeholder functionality for those browsers that don't support it.

https://github.com/marcgg/Simple-Placeholder

I searched through a lot of placeholder plugins before settling on this one and it works great so far. Originally found it in response to this similar question:

https://stackoverflow.com/questions/5120257/what-is-the-best-html5-placeholder-like-jquery-plugin-out-there

Diogo Cardoso

I recommend using Modernizr to detect this feature.

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

If you're not interested in using this library you could use the following the code.

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

Regarding to fallback support, if you're using jQuery you could use Simple Placeholder, which had its origin here at StackOverflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!