<input type="text">
text
类型的 <input>
元素创建基本的单行文本字段。
¥<input>
elements of type text
create basic single-line text fields.
Try it
值
¥Value
value
属性是一个字符串,包含在文本字段中输入的文本的当前值。你可以使用 JavaScript 中的 HTMLInputElement
value
属性来检索它。
¥The value
attribute is a string that contains the current value of the text entered into the text field. You can retrieve this using the HTMLInputElement
value
property in JavaScript.
let theText = myTextInput.value;
如果输入没有验证约束(有关更多详细信息,请参阅 验证),则该值可能是空字符串 (""
)。
¥If no validation constraints are in place for the input (see Validation for more details), the value may be an empty string (""
).
附加属性
list
列表属性的值是位于同一文档中的 <datalist>
元素的 id
。<datalist>
提供了一个预定义值列表来建议用户进行此输入。列表中与 type
不兼容的任何值都不包含在建议选项中。提供的值是建议,而不是要求:用户可以从此预定义列表中进行选择或提供不同的值。
¥The values of the list attribute is the id
of a <datalist>
element located in the same document. The <datalist>
provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type
are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.
maxlength
用户可以在 text
输入中输入的最大字符串长度(以 UTF-16 代码单元测量)。这必须是 0 或更大的整数值。如果未指定 maxlength
,或指定了无效值,则 text
输入没有最大长度。该值还必须大于或等于 minlength
的值。
¥The maximum string length (measured in UTF-16 code units) that the user can enter into the text
input. This must be an integer value of 0 or higher. If no maxlength
is specified, or an invalid value is specified, the text
input has no maximum length. This value must also be greater than or equal to the value of minlength
.
如果字段文本值的长度大于 maxlength
UTF-16 代码单元长,则输入将失败 约束验证。仅当用户更改值时才应用约束验证。
¥The input will fail constraint validation if the length of the text value of the field is greater than maxlength
UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
minlength
用户可以在 text
输入中输入的最小字符串长度(以 UTF-16 代码单位测量)。该值必须是小于或等于 maxlength
指定值的非负整数值。如果未指定 minlength
,或者指定了无效值,则 text
输入没有最小长度。
¥The minimum string length (measured in UTF-16 code units) that the user can enter into the text
input. This must be a non-negative integer value smaller than or equal to the value specified by maxlength
. If no minlength
is specified, or an invalid value is specified, the text
input has no minimum length.
如果输入字段的文本长度小于 minlength
UTF-16 代码单元长度,则输入将失败 约束验证。仅当用户更改值时才应用约束验证。
¥The input will fail constraint validation if the length of the text entered into the field is fewer than minlength
UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
pattern
指定时,pattern
属性是一个正则表达式,输入的 value
必须与该正则表达式匹配才能传递 约束验证 的值。它必须是有效的 JavaScript 正则表达式,如 RegExp
类型所使用的,以及我们的 正则表达式指南 中记录的;编译正则表达式时指定 'u'
标志,以便将模式视为 Unicode 代码点序列,而不是 ASCII。模式文本周围不应指定正斜杠。
¥The pattern
attribute, when specified, is a regular expression that the input's value
must match for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp
type, and as documented in our guide on regular expressions; the 'u'
flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.
如果指定的模式未指定或无效,则不应用正则表达式,并且完全忽略该属性。
¥If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
注意:使用
title
属性指定大多数浏览器将显示为工具提示的文本,以解释匹配模式的要求。你还应该在附近添加其他解释性文字。¥Note: Use the
title
attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.
有关更多详细信息和示例,请参阅 指定模式。
¥See Specifying a pattern for further details and an example.
placeholder
placeholder
属性是一个字符串,向用户提供有关该字段中期望的信息类型的简短提示。它应该是一个单词或短语,展示预期的数据类型,而不是解释性消息。文本不得包含回车或换行。
¥The placeholder
attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.
如果控件的内容具有一个方向性(LTR 或 RTL),但需要以相反的方向性呈现占位符,则可以使用 Unicode 双向算法格式化字符来覆盖占位符内的方向性;请参阅 如何使用 Bidi 文本的 Unicode 控件 了解更多信息。
¥If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.
注意:如果可以的话,请避免使用
placeholder
属性。它在语义上不如解释表单的其他方法那么有用,并且可能会导致内容出现意外的技术问题。请参阅<input>
可访问性问题 了解更多信息。¥Note: Avoid using the
placeholder
attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See<input>
accessibility concerns for more information.
readonly
布尔属性,如果存在,则意味着用户无法编辑该字段。然而,它的 value
仍然可以通过 JavaScript 代码直接设置 HTMLInputElement
value
属性来更改。
¥A Boolean attribute which, if present, means this field cannot be edited by the user. Its value
can, however, still be changed by JavaScript code directly setting the HTMLInputElement
value
property.
注意:由于只读字段不能有值,因此
required
对同时指定了readonly
属性的输入没有任何影响。¥Note: Because a read-only field cannot have a value,
required
does not have any effect on inputs with thereadonly
attribute also specified.
size
size
属性是一个数值,指示输入字段应有多少个字符宽。该值必须是大于零的数字,默认值为 20。由于字符宽度各不相同,因此这可能准确,也可能不准确,因此不应依赖于此;结果输入可能比指定的字符数更窄或更宽,具体取决于字符和字体(使用的 font
设置)。
¥The size
attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (font
settings in use).
这不会限制用户可以在该字段中输入的字符数。它仅指定一次大约可以看到多少个。要设置输入数据长度的上限,请使用 maxlength
属性。
¥This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength
attribute.
spellcheck
spellcheck
是一个全局属性,用于指示是否对元素启用拼写检查。它可以用于任何可编辑内容,但在这里我们考虑与在 <input>
元素上使用 spellcheck
相关的细节。spellcheck
的允许值为:
¥spellcheck
is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of spellcheck
on <input>
elements. The permitted values for spellcheck
are:
如果输入字段没有设置 readonly 属性且未禁用,则可以启用拼写检查。
¥An input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled.
如果 user agent's 首选项覆盖该设置,则读取 spellcheck
返回的值可能不会反映控件内拼写检查的实际状态。
¥The value returned by reading spellcheck
may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting.
非标准属性
autocorrect
mozactionhint
{{deprecated\_inline}}
一个 Mozilla 扩展,它提供有关如果用户在编辑字段时按 Enter 或 Return 键将采取何种操作的提示。
¥A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the Enter or Return key while editing the field.
已弃用:请改用 enterkeyhint
。
¥Deprecated: Use enterkeyhint
instead.
使用文本输入
¥Using text inputs
text
类型的 <input>
元素创建基本的单行输入。你应该在希望用户输入单行值的任何地方使用它们,并且没有更具体的输入类型可用于收集该值(例如,如果它是 date、URL、email 或 搜索词,你已经 有更好的选择)。
¥<input>
elements of type text
create basic, single-line inputs. You should use them anywhere you want the user to enter a single-line value and there isn't a more specific input type available for collecting that value (for example, if it's a date, URL, email, or search term, you've got better options available).
基本示例
¥Basic example
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name" />
</div>
<div>
<button>Submit</button>
</div>
</form>
呈现如下:
¥This renders like so:
提交时,发送到服务器的数据名称/值对将为 name=Chris
(如果提交前输入了 "克里斯" 作为输入值)。你必须记住在 <input>
元素上包含 name
属性,否则文本字段的值将不会包含在提交的数据中。
¥When submitted, the data name/value pair sent to the server will be name=Chris
(if "Chris" was entered as the input value before submission). You must remember to include name
attribute on the <input>
element, otherwise the text field's value won't be included with the submitted data.
设置占位符
¥Setting placeholders
你可以在文本输入中提供有用的占位符,通过使用 placeholder
属性来提供有关输入内容的提示。看下面的例子:
¥You can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the placeholder
attribute. Look at the following example:
<form>
<div>
<label for="uname">Choose a username: </label>
<input
type="text"
id="uname"
name="name"
placeholder="Lower case, all one word" />
</div>
<div>
<button>Submit</button>
</div>
</form>
你可以在下面看到占位符的呈现方式:
¥You can see how the placeholder is rendered below:
占位符通常以比元素前景色更亮的颜色呈现,并且当用户开始在字段中输入文本时(或者每当字段通过设置其 value
属性以编程方式设置值时),占位符会自动消失。
¥The placeholder is typically rendered in a lighter color than the element's foreground color, and automatically vanishes when the user begins to enter text into the field (or whenever the field has a value set programmatically by setting its value
attribute).
物理输入元素大小
¥Physical input element size
输入框的物理尺寸可以使用 size
属性来控制。使用它,你可以指定文本输入一次可以显示的字符数。这会影响元素的宽度,让你可以以字符而不是像素来指定宽度。例如,在此示例中,输入的宽度为 30 个字符:
¥The physical size of the input box can be controlled using the size
attribute. With it, you can specify the number of characters the text input can display at a time. This affects the width of the element, letting you specify the width in terms of characters rather than pixels. In this example, for instance, the input is 30 characters wide:
<form>
<div>
<label for="uname">Choose a username: </label>
<input
type="text"
id="uname"
name="name"
placeholder="Lower case, all one word"
size="30" />
</div>
<div>
<button>Submit</button>
</div>
</form>
验证
¥Validation
text
类型的 <input>
元素没有应用自动验证(因为基本文本输入需要能够接受任何任意字符串),但有一些可用的客户端验证选项,我们将在下面讨论。
¥<input>
elements of type text
have no automatic validation applied to them (since a basic text input needs to be capable of accepting any arbitrary string), but there are some client-side validation options available, which we'll discuss below.
注意:HTML 表单验证不能替代确保输入数据格式正确的服务器脚本。对于某人来说,对 HTML 进行调整以绕过验证或完全删除它太容易了。其他人也有可能完全绕过你的 HTML 并将数据直接提交到你的服务器。如果你的服务器端代码无法验证其接收到的数据,则当格式不正确的数据(或数据太大、类型错误等)输入数据库时,可能会发生灾难。
¥Note: HTML form validation is not a substitute for server-scripts that ensure the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.
关于样式的注意事项
¥A note on styling
有一些有用的伪类可用于设置表单元素的样式,以帮助用户查看其值何时有效或无效。它们是 :valid
和 :invalid
。在本节中,我们将使用以下 CSS,它将在包含有效值的输入旁边放置一个复选(勾号)标记,并在包含无效值的输入旁边放置一个十字 (X)。
¥There are useful pseudo-classes available for styling form elements to help the user see when their values are valid or invalid. These are :valid
and :invalid
. In this section, we'll use the following CSS, which will place a check (tick) mark next to inputs containing valid values, and a cross (X) next to inputs containing invalid values.
div {
margin-bottom: 10px;
position: relative;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
}
该技术还要求将 <span>
元素放置在表单元素之后,该元素充当图标的支架。这是必要的,因为某些浏览器上的某些输入类型不能很好地显示直接放置在它们后面的图标。
¥The technique also requires a <span>
element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well.
要求输入
¥Making input required
你可以使用 required
属性作为在允许表单提交之前输入所需值的简单方法:
¥You can use the required
attribute as an easy way of making entering a value required before form submission is allowed:
<form>
<div>
<label for="uname">Choose a username: </label>
<input type="text" id="uname" name="name" required />
<span class="validity"></span>
</div>
<div>
<button>Submit</button>
</div>
</form>
div {
margin-bottom: 10px;
position: relative;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
}
呈现如下:
¥This renders like so:
如果你尝试在未输入搜索词的情况下提交表单,浏览器将显示一条错误消息。
¥If you try to submit the form with no search term entered into it, the browser will show an error message.
输入值长度
¥Input value length
你可以使用 minlength
属性指定输入值的最小长度(以字符为单位);同样,使用 maxlength
设置输入值的最大长度(以字符为单位)。
¥You can specify a minimum length (in characters) for the entered value using the minlength
attribute; similarly, use maxlength
to set the maximum length of the entered value, in characters.
下面的示例要求输入的值长度为 4-8 个字符。
¥The example below requires that the entered value be 4–8 characters in length.
<form>
<div>
<label for="uname">Choose a username: </label>
<input
type="text"
id="uname"
name="name"
required
size="10"
placeholder="Username"
minlength="4"
maxlength="8" />
<span class="validity"></span>
</div>
<div>
<button>Submit</button>
</div>
</form>
div {
margin-bottom: 10px;
position: relative;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
}
呈现如下:
¥This renders like so:
如果你尝试提交少于 4 个字符的表单,你将收到一条相应的错误消息(该消息因浏览器而异)。如果你尝试输入超过 8 个字符,浏览器将不允许你输入。
¥If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to enter more than 8 characters, the browser won't let you.
注意:如果指定
minlength
但未指定required
,则输入被视为有效,因为用户不需要指定值。¥Note: If you specify a
minlength
but do not specifyrequired
, the input is considered valid, since the user is not required to specify a value.
指定模式
¥Specifying a pattern
你可以使用 pattern
属性指定输入值必须匹配的正则表达式才能被视为有效(有关使用正则表达式验证输入的简单速成课程,请参阅 根据正则表达式进行验证)。
¥You can use the pattern
attribute to specify a regular expression that the inputted value must match in order to be considered valid (see Validating against a regular expression for a simple crash course on using regular expressions to validate inputs).
下面的示例将值限制为 4-8 个字符,并要求它仅包含小写字母。
¥The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.
<form>
<div>
<label for="uname">Choose a username: </label>
<input
type="text"
id="uname"
name="name"
required
size="45"
pattern="[a-z]{4,8}" />
<span class="validity"></span>
<p>Usernames must be lowercase and 4-8 characters in length.</p>
</div>
<div>
<button>Submit</button>
</div>
</form>
div {
margin-bottom: 10px;
position: relative;
}
p {
font-size: 80%;
color: #999;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
}
呈现如下:
¥This renders like so:
示例
¥Examples
你可以在我们的 你的第一个 HTML 表单 和 如何构建 HTML 表单 文章中看到在上下文中使用文本输入的好示例。
¥You can see good examples of text inputs used in context in our Your first HTML form and How to structure an HTML form articles.
技术总结
¥Technical summary
值 | 表示文本字段中包含的文本的字符串。 | |
活动 | change 和 input |
|
支持的通用属性 |
autocomplete 、
list 、
maxlength 、
minlength 、
pattern 、
placeholder 、
readonly 、
required 和
size
|
|
IDL 属性 | list , value |
|
DOM 接口 | ||
方法 | select() 、setRangeText() 和 setSelectionRange() 。 |
|
隐式 ARIA 角色 |
没有 list 属性:
textbox
|
具有 list 属性: combobox |
规范
Specification |
---|
HTML Standard # text-(type=text)-state-and-search-state-(type=search) |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also
- HTML 表单
<input>
及其所基于的HTMLInputElement
接口。<input type="search">
<textarea>
:多行文本输入- CSS 属性的兼容性