最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to detect whether an HTML5 input control is supported? - Stack Overflow

programmeradmin0浏览0评论

If I put a <input type="range"> control on a form, some browsers will (correctly) render a slider control, and others won't know what range is and will render a textbox instead. Handling this case would require extra validation, as a textbox can contain any arbitrary text. Is there any JavaScript I can put into the page to say "look at this control in the DOM, and if it's a textbox control, do foo()"?

If I put a <input type="range"> control on a form, some browsers will (correctly) render a slider control, and others won't know what range is and will render a textbox instead. Handling this case would require extra validation, as a textbox can contain any arbitrary text. Is there any JavaScript I can put into the page to say "look at this control in the DOM, and if it's a textbox control, do foo()"?

Share Improve this question asked Apr 10, 2013 at 0:15 Mason WheelerMason Wheeler 84.7k54 gold badges285 silver badges505 bronze badges 1
  • possible duplicate of How to check, if a HTML5 input is supported? – Evan Davis Commented Apr 10, 2013 at 0:20
Add a ment  | 

1 Answer 1

Reset to default 11

This site remends using Modernizer:

Checking for HTML5 input types uses detection technique #4. First, you create a dummy <input> element in memory. The default input type for all <input> elements is "text". This will prove to be vitally important.

var i = document.createElement("input");

Next, set the type attribute on the dummy element to the input type you want to detect.

i.setAttribute("type", "color");

If your browser supports that particular input type, the type property will retain the value you set. If your browser doesn't support that particular input type, it will ignore the value you set and the type property will still be "text".

return i.type !== "text";

Instead of writing 13 separate functions yourself, you can use Modernizr to detect support for all the new input types defined in HTML5. Modernizr reuses a single <input> element to efficiently detect support for all 13 input types. Then it builds a hash called Modernizr.inputtypes, that contains 13 keys (the HTML5 type attributes) and 13 Boolean values (true if supported, false if not).

//check for native date picker
if (!Modernizr.inputtypes.date) {
  // no native support for <input type="date"> :(
  // maybe build one yourself with Dojo or jQueryUI
}
发布评论

评论列表(0)

  1. 暂无评论