javascript – 如何检测输入类型

似乎无法在这里找到一个无Modernizr的解决方案,但我如何检测对特定输入类型的支持,而不是属性?

例如,对于属性:

var supportsRequired = 'required' in document.createElement('input')
if (supportsRequired) {
    // support
} else {
    // no support
}

使用输入类型有一种简单的方法吗?我不想做的一件事是,如果不支持,则“交换”输入类型.有没有类似的东西,只测试?…

var supportsEmailType = 'email' in input.type
if (supportsEmailType) {
    // support
} else {
    // no support
}

任何帮助赞赏.

最佳答案 从
here开始:

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”.

这将正确检测是否支持“email”类型,您可以重用该函数来检测其他类型:

if (supportsInputType('email')) {
    // support
} else {
    // no support
}

function supportsInputType(type){
    var i = document.createElement('input');
    i.setAttribute('type', type);
    return i.type === type;
}
点赞