你想知道的所有关于inputmode的事情,这里都有

2,731 阅读3分钟

温馨提示:当前为翻译自https://css-tricks.com/everything-you-ever-wanted-to-know-about-inputmode/的初稿,轻喷!

简介

inputmode全局属性,提供了一种机制让开发者可以定制inputtextarea元素需要的键盘类型。

<input type="text" inputmode="" />
<textarea inputmode="" />

type属性不同的是,inputmode属性并不会改变浏览器对input的处理。它仅仅是决定如何展示键盘。

inputmode属性由来已久,但是仅仅在最近几年才被主流的Safari和Chrome实现。在此之前,仅仅在2012年被Firefox实现过,不幸的是,没几个月后就被挪出了。六年后(2018年),input又被主流浏览器统统实现了。

当前的浏览器兼容性如下图:

iunputmode拥有一系列的属性值。让我们挨个过一遍。

属性值

None

<input type="text" inputmode="none" />

顾名思义,弹出默认键盘。

Numeric

<input type="text" inputmode="numeric" />

数字键盘是开发中最常见的需求,比如说:PIN,zip codes,信用卡,手机号等等。使用numeric伴随type=text会比单独使用type=number更有意义。 因为inputmode="numeric"可以结合maxlength minlength pattern 属性一起使用,会变得更适应各种使用场景。 我之前经常看到网站都在使用type=tel,但是往往不能展示正确。当我们使用inputmode,可以同时为input加上pattern="\d*"来实现同样的效果。

Tel

<input type="text" inputmode="tel" />

使用标准的键盘输入手机号一直都是一个痛点。 使用inputmode=tel将会提供一个标准的手机号输入键盘。

Decimal

<input type="text" inputmode="decimal" />

这个属性值仅仅在苹果系统上有效果,在安卓手机上没有任何效果。所以,建议直接使用numeric就可以了。

Email

<input type="text" inputmode="email" />

我非常确定你在填写邮件表单的时候,都需要切换键盘类型,来选中@符号,这虽然不是非常严重致命的问题,但是总归不是一个好的体验。

随着email属性值的到来,也带来了@.

当我们在登陆twitter的时候,这也特别有用。 另外一种使用场景验证邮件正确性。

URL

<input type="text" inputmode="url" />

这个属性值提供了一种让用户可以非常简单地使用.com,.co.uk的方式。就像是在url地址中输入./字符。准备的键盘样式依赖于用户的使用语言。这个属性值让用户输入url变得非常的便利。

Search

<input type="text" inputmode="search" />

很明显,键盘上会出现蓝色按钮Go或者Return(中文:搜索,确认) 。Search在搜索框还是非常有用的,提供了快捷的提交查询按钮。

其他你可能需要知道的事情

  • Chromium-based browsers on Android — such as Microsoft Edge, Brave and Opera — share the same inputmode behavior as Chrome.
  • I haven’t included details of keyboards on iPad for the sake of brevity. It’s mostly the same as iPhone but includes more keys. Same is true for Android tablets, save for third-party keyboards, which might be another topic worth covering.
  • The original proposed spec had the values kana and katakana for Japanese input but they were never implemented by any browser and have since been removed from the spec.
  • latin-name was also one of the values of the original spec and has since been removed. Interestingly, if it’s used now on Safari for iOS, it will display the user’s name as a suggestion above the keyboard.

Demo

喔,你迫不及待想看这些属性值各自的效果了吧?点击打开 demo ,你可以用手机打开来看到各个输入框对应的键盘效果。