欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

表单的输入类型_HTML5表单:输入类型(第1部分)

程序员文章站 2022-06-10 14:06:47
...

表单的输入类型

The following is an extract from our book, HTML5 & CSS3 for the Real World, 2nd Edition, written by Alexis Goldstein, Louis Lazaris, and Estelle Weyl. Copies are sold in stores worldwide, or you can buy it in ebook form here.

以下摘自Alexis Goldstein,Louis Lazaris和Estelle Weyl编写的《现实世界HTML5和CSS3,第二版 》一书。 副本在世界各地的商店中都有出售,您也可以在这里以电子书的形式购买。

You’re probably already familiar with the input element’s type attribute. This is the attribute that determines what kind of form input will be presented to the user. If it is omitted—or in the case of new input types and older browsers, not understood—it still works; the input will default to type="text". This is the key that makes HTML5 forms usable today even if you’re still supporting older browsers. If you use a new input type, such as email or search, older browsers will simply present users with a standard text field.

您可能已经熟悉input元素的type属性。 这是确定将哪种形式的表单输入呈现给用户的属性。 如果省略它(或者在新的输入类型和较旧的浏览器的情况下无法理解),它仍然有效; 输入将默认为type="text" 。 即使您仍在支持旧版浏览器,这也是使HTML5表单在今天可用的关键。 如果您使用新的输入类型,例如emailsearch ,则旧的浏览器将仅向用户显示标准文本字段。

Our sign-up form currently uses four of the ten input types you’re familiar with: checkbox, text,password, and submit. Here’s the full list of types that were available before HTML5:

我们的注册表单目前使用您熟悉的十种输入类型中的四种: checkboxtextpasswordsubmit 。 这是HTML5之前可用的类型的完整列表:

  • button

    button

  • checkbox

    checkbox

  • file

    file

  • hidden

    hidden

  • image

    image

  • password

    password

  • radio

    radio

  • reset

    reset

  • submit

    submit

  • text

    text

The HTML5 specification gave us nine more input types that provide for more data-specific UI elements and native data validation:

HTML5规范为我们提供了另外九种输入类型,它们提供了更多特定于数据的UI元素和本机数据验证:

  • search

    search

  • email

    email

  • url

    url

  • tel

    tel

  • date

    date

  • time

    time

  • number

    number

  • range

    range

  • color

    color

HTML5.1 and the WHATWG HTML Living Standard includes four additional date input types, three of which are well supported in modern browsers:

HTML5.1和WHATWG HTML Living Standard包括四种附加的日期输入类型,现代浏览器很好地支持其中三种:

  • datetime-local

    datetime-local

  • month

    month

  • week

    week

  • datetime

    datetime

  • (not supported in any browser)

    (任何浏览器均不支持)

Let’s look at each of these new types in detail, and see how we can put them to use.

让我们详细研究每种新类型,并了解如何使用它们。

搜索 (Search)

The search input type (type="search") provides a search field—a one-line text input control for entering one or more search terms. The spec states:

search输入类型( type="search" )提供一个搜索字段-用于输入一个或多个搜索词的单行文本输入控件。 规范指出:

The difference between the text state and the search state is primarily stylistic: on platforms where search fields are distinguished from regular text fields, the search state might result in an appearance consistent with the platform’s search fields rather than appearing like a regular text field.

文本状态和搜索状态之间的区别主要是风格:在将搜索字段与常规文本字段区分开的平台上,搜索状态可能会导致外观与平台的搜索字段一致,而不是看起来像常规文本字段。

Many browsers style search inputs in a manner consistent with the browser or the operating system’s search boxes. Currently, Chrome, Safari, Opera, and IE have added the ability to clear the input with the click of a mouse by providing an × icon once text is entered into the field, as shown in Figure 4.5. The date/time input types are also clearable in Chrome and Opera, and IE11 includes an × icon to clear most input types now, including inputs of type text.

许多浏览器以与浏览器或操作系统的搜索框一致的方式设置搜索输入的样式。 当前,Chrome,Safari,Opera和IE已添加了在文本输入字段后提供一个×图标来清除输入的功能,如图4.5所示。 日期/时间输入类型在Chrome和Opera中也可以清除,IE11包含一个×图标,现在可以清除大多数输入类型,包括文本类型的输入。

表单的输入类型_HTML5表单:输入类型(第1部分)

Figure 4.5. The search input type is styled to resemble the operating system’s search fields

图4.5。 搜索输入类型的样式类似于操作系统的搜索字段

On Apple devices, the search field has rounded corners by default in Chrome, Safari, and Opera, matching the devices’ search field appearance. On touch pads with dynamic keyboards, the “go” button appears as a search icon or the word “search,” depending on the device. If you include the non-standard results attribute, Chrome and Opera will display a magnifying/looking glass icon within the form field.

在Apple设备上,默认情况下,Chrome,Safari和Opera中的搜索字段带有圆角,与设备的搜索字段外观匹配。 在带有动态键盘的触摸板上,“ go”按钮将显示为搜索图标或单词“ search”,具体取决于设备。 如果您包含非标准结果属性,Chrome和Opera将在表单字段中显示一个放大镜/镜象。

While you can still use type="text" for search fields, the new search type is a visual cue as to where the user needs to go to search the site, and provides an interface to which the user is accustomed. The HTML5 Herald has no search field, but here’s an example of how you’d use it:

尽管您仍然可以在搜索字段中使用type="text" ,但是新的搜索类型是用户需要去哪里搜索站点的直观提示,并提供了用户习惯的界面。 HTML5 Herald没有搜索字段,但是下面是您如何使用它的示例:

<form id="search" method="get"> 
  <label for="s">Search</label> 
  <input type="search" id="s" name="s"/> 
  <input type="submit" value="Search"/> 
</form>

Since search, like all the new input types, appears as a regular text box in nonsupporting browsers, there’s no reason not to use it when appropriate.

由于search,与所有新的输入类型一样,在不支持的浏览器中显示为常规文本框,因此没有理由在适当的时候不使用它。

电子邮件地址 (Email Addresses)

The email type (type="email") is, not surprisingly, used for specifying one or more email addresses. It supports the Boolean multiple attribute, allowing for multiple comma-separated (with optional space) email addresses.

毫不奇怪, email类型(type="email")用于指定一个或多个电子邮件地址。 它支持布尔multiple属性,允许使用多个逗号分隔(带有可选空格)的电子邮件地址。

Let’s change our form to use type="email" for the registrant’s email address:

让我们更改表单,以将type="email"用作注册者的电子邮件地址:

<label for="email">My email address is</label> 
<input type="email" id="email" name="email"/>

If you change the input type from text to email, as we’ve done here, you’ll notice no visible change in the user interface; the input still looks like a plain text field. However, there are differences behind the scenes.

如果您将输入类型从text更改为email ,就像我们在此处所做的那样,您会注意到用户界面中没有可见的更改。 输入仍然看起来像纯文本字段。 但是,幕后存在差异。

The change becomes apparent if you’re using a touchpad device. When you focus on the email field, most touchpad devices—such as the iPad or Android phone running Chromium—will all display a keyboard optimized for email entry, including the @ symbol, period, and space buttons, but no comma, as shown in Figure 4.6.

如果您使用的是触摸板设备,则更改会很明显。 当您专注于电子邮件字段时,大多数触摸板设备(例如运行Chromium的iPad或Android手机)都将显示针对电子邮件输入进行了优化的键盘,包括@符号,点号和空格按钮,但没有逗号,如图所示。图4.6。

表单的输入类型_HTML5表单:输入类型(第1部分)

Figure 4.6. The email input type provides a custom keyboard on iOS devices

图4.6。 电子邮件输入类型在iOS设备上提供了自定义键盘

Firefox, Chrome, Opera, and Internet Explorer 10 also provide error messaging for invalid email inputs: if you try to submit a form with content unrecognizable as one or more email addresses, the browser will tell you what’s wrong. The default error messages are shown in Figure 4.7.

Firefox,Chrome,Opera和Internet Explorer 10还为错误的电子邮件输入提供错误消息:如果您尝试提交一个表单,该表单的内容无法识别为一个或多个电子邮件地址,浏览器将告诉您出了什么问题。 默认错误消息如图4.7所示。

表单的输入类型_HTML5表单:输入类型(第1部分)

Figure 4.7. Error messages for incorrectly formatted email addresses on Opera (left) and Firefox (right)

图4.7。 Opera(左)和Firefox(右)上错误格式的电子邮件地址的错误消息

Note: Custom Validation Messages

注意:自定义验证消息

Dislike the default error messages the browsers provide? Set your own with .setCustomValidity(errorMsg). setCustomValidity takes as its only parameter the error message you want to provide. If you set a custom validation message, once that value becomes valid you must set the validation message to an empty string (a falsy value) to enable form submission:

不喜欢浏览器提供的默认错误消息吗? 使用.setCustomValidity(errorMsg)setCustomValidity将要提供的错误消息作为其唯一参数。 如果设置自定义验证消息,则该值变为有效后,必须将验证消息设置为空字符串(伪造的值)以启用表单提交:

function setErrorMessages(formControl) {
  var validityState_object = formControl.validity;
  if (validityState_object.valueMissing) {
      formControl.setCustomValidity('Please set an age 
↵(required)');  
  } else if (validityState_object.rangeUnderflow) {
      formControl.setCustomValidity('You\'re too young');
  } else if (validityState_object.rangeOverflow) {
      formControl.setCustomValidity('You\'re too old');
  } else if (validityState_object.stepMismatch) {
      formControl.setCustomValidity('Counting half 
↵birthdays?');
  } else {
      //if valid, must set falsy value or will always error 
      formControl.setCustomValidity('');
  }
}

Unfortunately, while you can change the content of the message, you’re stuck with its appearance, at least for now.

不幸的是,尽管您可以更改消息的内容,但至少在现在,您仍然无法确定其外观。

网址 (URLs)

The url input (type="url") is used for specifying a web address. Much like email, it will appear as a normal text field. On many touch screens, the onscreen keyboard displayed will be optimized for web address entry, with a forward slash (/) and a “.com” shortcut key.

url输入(type="url")用于指定网址。 就像email一样,它将显示为普通文本字段。 在许多触摸屏上,显示的屏幕键盘将使用正斜杠(/)和“ .com”快捷键针对网址输入进行优化。

Let’s update our registration form to use the url input type:

让我们更新注册表格以使用url输入类型:

<label for="url">My website is located at:</label> 
<input type="url" id="url" name="url"/>

网址验证 (Validation of URLs)

All modern browsers starting with Internet Explorer 10 support the url input type, reporting the input as invalid if the value doesn’t begin with a protocol. Only the general protocol format of a URL is validated, so, for example, q://example.xyz will be considered valid, even though q:// isn’t a real protocol and .xyz isn’t a real top-level domain. If you want the value entered to conform to a more specific format, provide information in your label (or in a placeholder) to let your users know, and use the pattern attribute to ensure that it’s correct, as previously described.

从Internet Explorer 10开始的所有现代浏览器都支持url输入类型,如果该值不是以协议开头的,则将输入报告为无效。 仅验证URL的常规协议格式,因此,即使q://不是真实的协议,而.xyz不是真实的top-,例如q://example.xyz也将被视为有效。级别域。 如果希望输入的值符合更特定的格式,请按照前面的描述,在标签(或占位符)中提供信息以使用户知道,并使用pattern属性确保其正确。

电话号码 (Telephone Numbers)

For telephone numbers, use the tel input type (type="tel"). Unlike the url and email types, the tel type doesn’t enforce a particular syntax or pattern. Letters and numbers—indeed, any characters other than new lines or carriage returns—are valid. There’s a good reason for this: all over the world, countries have valid phone numbers of various lengths and punctuation, so it would be impossible to specify a single format as standard. For example, in the USA, +1(415)555-1212 is just as well understood as 415.555.1212, but companies may also use letters in their phone number, such as (800)CALL-NOW.

对于电话号码,请使用tel输入类型(type="tel") 。 与urlemail类型不同,tel类型不强制使用特定的语法或模式。 字母和数字(实际上是换行符或回车符以外的任何字符)均有效。 这是有充分的理由的:在世界各地,国家/地区都有有效的电话号码,包括各种长度和标点符号,因此不可能将单一格式指定为标准格式。 例如,在美国,+ 1(415)555-1212与415.555.1212一样好理解,但是公司也可以在其电话号码中使用字母,例如(800)CALL-NOW。

You can encourage a particular format by including a placeholder with the correct syntax, or a comment after the input with an example. Additionally, you can stipulate a format by using the pattern attribute. Include a title with the pattern attribute to provide for a tooltip and to improve the UX of the native validation error message. You can also use the setCustomValidity method to provide more informative client-side validation.

您可以通过使用带有正确语法的占位符或输入示例后的注释来鼓励使用特定格式。 此外,您可以使用pattern属性指定格式。 在pattern属性中包含标题,以提供工具提示并改善本机验证错误消息的UX。 您还可以使用setCustomValidity方法来提供更多有用的客户端验证。

In using the tel input type, dynamic touch pads will usually display the telephone keyboard, including the asterisk and pound key. You can use tel for more than just phone numbers. For example, it is likely to be the best keypad for social security number form entry.

在使用tel输入类型时,动态触摸板通常会显示电话键盘,包括星号和井号键。 您可以使用tel不仅仅是电话号码。 例如,它可能是用于输入社会安全号码表格的最佳键盘。

翻译自: https://www.sitepoint.com/html5-forms-input-types/

表单的输入类型