我知道我们可以使用JavaScript。
if (typeof textbox === "object") { }
但是是否有方法可以确保该对象是文本框?
我知道我们可以使用JavaScript。
if (typeof textbox === "object") { }
但是是否有方法可以确保该对象是文本框?
var isInputText = obj instanceof HTMLInputElement && obj.type == 'text';
window.HTMLInputElement === otherWindow.HTMLInputElement
将为false,因此instanceof
运算符也可能意外返回false。同样适用于iframe和弹出窗口。在这些情况下,检查tagName
可以起作用,就像其他答案已经提到的那样。 - John Weisz截至2016年,请使用以下内容:
function isTextBox(element) {
var tagName = element.tagName.toLowerCase();
if (tagName === 'textarea') return true;
if (tagName !== 'input') return false;
var type = element.getAttribute('type').toLowerCase(),
// if any of these input types is not supported by a browser, it will behave as input type text.
inputTypes = ['text', 'password', 'number', 'email', 'tel', 'url', 'search', 'date', 'datetime', 'datetime-local', 'time', 'month', 'week']
return inputTypes.indexOf(type) >= 0;
}
'tel'
。 - Shaun Lebronelement.isContentEditable
。 - Poul Kruijtelement.isContentEditable
对于可编辑的输入框可能为 false,因此不要依赖它为 true。readonly
属性也可能是相关的。 - Tamzin BlakeinputTypes.contains is not a function
,代码看起来像是一个修改过的版本,包括完全相同的注释。在GitHub上找不到这段代码,也找不到在我的机器上的任何地方。最后发现这是来自RoboForm密码管理器。在GitHub上还有多个仓库有着完全相同的注释。所有的版本都有不同程度的修改...这太疯狂了。 - undefined你是否正在寻找像这样的东西?
if(textbox.tagName && textbox.tagName.toLowerCase() == "textarea") {
alert('this is a textarea');
}
如果你需要判断是否为文本输入框,可以这样做:
if(textbox.tagName && textbox.tagName.toLowerCase() == "input" && textbox.type.toLowerCase() == "text") {
alert('this is a text input');
}
if (textbox.tagName == "input" && textbox.getAttribute("type") == "text") {
// it's a text input
}
if(textbox instanceof HTMLInputElement && textbox.getAttribute("type") == "text") {
alert("I'm an input text element");
}
我认为你可能想要获取一个元素的引用,然后检查 .type 的返回值,即
var element = document.getElementById('element_in_question');
if(element.type == "textarea"){
console.log('I must be textarea');
}
evt.target.type
给我的是“text”。 - Polv