Javascript 如何判断浏览器是否支持 <input type='date'>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10193294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:15:38  来源:igfitidea点击:

How can I tell if a browser supports <input type='date'>

javascripthtml

提问by DaedalusFall

Possible Duplicate:
HTML5 Type Detection and Plugin Initialization

可能的重复:
HTML5 类型检测和插件初始化

<input type=date>

Should create an input with an (optional) user-agent provided datepicker, but its not widely supported yet, so we're using a jQuery UI Datepicker. How can we allow browsers to use their own datepicker and fall back on jQuery UI only if the browser doesn't have such a thing?

应该使用(可选)用户代理提供的日期选择器创建输入,但它尚未得到广泛支持,因此我们使用 jQuery UI 日期选择器。我们如何才能允许浏览器使用自己的日期选择器并仅在浏览器没有这样的东西时才使用 jQuery UI?

At present I think only Opera has a built in datepicker, but a test for Opera would obviously be bad. Is there a way this feature can be detected (if it can at all in a portable manner)?

目前我认为只有 Opera 有内置的日期选择器,但对 Opera 的测试显然很糟糕。有没有办法检测到这个功能(如果它可以以便携的方式)?

回答by Italo Borssatto

The method bellow checks if some input type is supported by most of the browsers:

下面的方法检查大多数浏览器是否支持某些输入类型:

function checkInput(type) {
    var input = document.createElement("input");
    input.setAttribute("type", type);
    return input.type == type;
}

But, as simonoxmentioned in the comments, some browsers (as Android stock browsers) pretend that they support some type (as date), but they do not offer an UI for date inputs. So simonoximproved the implementation using the trick of setting an illegal value into the date field. If the browser sanitises this input, it could also offer a datepicker!!!

但是,正如评论中提到的simonox,一些浏览器(如 Android 股票浏览器)假装它们支持某种类型(如日期),但它们不提供用于日期输入的 UI。因此,simonox使用在日期字段中设置非法值的技巧改进了实现。如果浏览器清理了这个输入,它也可以提供一个日期选择器!!!

function checkDateInput() {
    var input = document.createElement('input');
    input.setAttribute('type','date');

    var notADateValue = 'not-a-date';
    input.setAttribute('value', notADateValue); 

    return (input.value !== notADateValue);
}