检查输入是否属于“文本/数字/电子邮件/等"类型? [英] Check if input is of type "text/number/email/etc"?

查看:38
本文介绍了检查输入是否属于“文本/数字/电子邮件/等"类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Javascript(不是 jQuery)检查给定的输入元素是否可由用户使用键盘写入.

I need to check with Javascript (not jQuery) if the given input element is writable by the user using the keyboard.

我想排除复选框、单选按钮、按钮、重置、提交、图像等.

I'd like to exclude checkboxes, radios, buttons, resets, submits, image and so on.

是否有一种简单的方法可以在不列出所有输入类型的情况下做到这一点?

Is there a simple way to do it without list all the input types?

这是我现在的代码:

if (element.getAttribute === undefined) {
    return false;
}

var eTag  = element.tagName;
var eType = element.getAttribute('type');
var isTextInput = (eTag === 'INPUT' || eTag === 'TEXTAREA') && ( eType !== null || eType === 'text' || eType === 'password');
var isEnabledInput = element.disabled === false && element.readOnly === false;
var isContentEditable = ( element.contentEditable && element.contentEditable === true );

// stop for enabled text inputs, selects and contentEditable areas
return (isTextInput && isEnabledInput) || eType === 'SELECT' || isContentEditable;

逻辑上&&( eType !== null || eType === 'text' || eType === 'password'); 不足以全部检查.

Logically the && ( eType !== null || eType === 'text' || eType === 'password'); is not enough to check them all.

推荐答案

将此作为答案发布是因为解决了问题,但这并不是我所要求的.

Posting this as an answer because fixes the problem, but it's not strictly what I'm asking for.

我仍在等待更简洁的解决方案.

I'm still waiting for a cleaner solution.

var notTextual = [
    'button',
    'checkbox',
    'hidden',
    'image',
    'radio',
    'reset',
    'submit'
];

if (element.getAttribute === undefined) {
    return false;
}

var eTag  = element.tagName;
var eType = element.getAttribute('type');
var isTextInput = (eTag === 'INPUT' || eTag === 'TEXTAREA') && !notTextual.contains(eType);
var isEnabledInput = element.disabled === false && element.readOnly === false;
var isContentEditable = ( element.contentEditable && element.contentEditable === true );

// stop for enabled text inputs, selects and contentEditable areas
return (isTextInput && isEnabledInput) || eType === 'SELECT' || isContentEditable;

这篇关于检查输入是否属于“文本/数字/电子邮件/等"类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆