如何用 inputmode 和 autocomplete 优化移动端表单输入
移动端表单想少出错、少打字,记住两条:键盘类型交给 inputmode,字段语义交给 autocomplete。前者决定用户点开输入框时弹出什么键盘,后者决定浏览器能不能直接帮你把姓名、地址、卡号填进去——两者职责完全不同,写 autocomplete="email" 不会让键盘冒出 @,写 inputmode="numeric" 也不会让浏览器记住你的手机号。
inputmode 和 type="number" 有什么区别?
结论:inputmode 只影响软键盘布局,不改变元素的取值语义;type="number" 会改变 value 的解析规则,在手机号、卡号、身份证这类场景里反而是坑。
type="number" 有三个移动端常见问题:一是允许输入 e、+、-;二是用户输入非法内容时 input.value 读到的是空字符串 "",前端拿不到原始文本;三是桌面上滚动滚轮会意外改值,且前导 0 会被吃掉(邮编 012345 变 12345)。
所以手机号、邮编、验证码、卡号统一用 type="text" 或 type="tel",键盘需求交给 inputmode:
<!-- 金额:需要小数点 -->
<input type="text" inputmode="decimal" name="amount">
<!-- 验证码 / 数量:只要 0-9 -->
<input type="text" inputmode="numeric" name="code">
<!-- 手机号:要能敲 + - -->
<input type="tel" inputmode="tel" name="mobile">
inputmode 的取值只有这几个:none、text、decimal、numeric、tel、search、email、url。选值原则是按「用户实际要敲的字符集」从宽不从窄。
inputmode 各字段该怎么选?兼容性够吗?
结论:按字符集选值即可;兼容性上 Chrome 66+、桌面 Safari 12.1+、iOS Safari 12.2+、Firefox 95+ 都支持,更老的 iOS 可以用 pattern 兜底。
- 金额、重量、价格 →
inputmode="decimal",注意部分地区小数点渲染成逗号,服务端解析要同时兼容,和. - 验证码、年龄、门牌号 →
inputmode="numeric"(纯数字键盘) - 手机号、座机 →
inputmode="tel"(带+ * #的电话键盘) - 邮箱 →
inputmode="email",网址 →inputmode="url",搜索框 →inputmode="search"
对于不认 inputmode 的老 iOS Safari,加 pattern="[0-9]*" 能触发数字键盘:<input type="tel" pattern="[0-9]*" inputmode="numeric">。注意 pattern 在移动端只做键盘提示,它不替代校验,必填和格式校验必须放在服务端再做一遍。
autocomplete 怎么写才能真正触发自动填充?
结论:必须使用规范里的标准 token,一个字段一个 token,并把 name 属性和 <label for> 关联写对;autocomplete="off" 在密码、地址字段上基本会被 Chrome 和 Safari 忽略。
常用 token 按场景记:
| 场景 | 写法 |
|---|---|
| 姓名 | given-name / family-name / name |
| 联系方式 | email / tel |
| 地址 | street-address / address-line1 / address-level1(省)/ address-level2(市)/ postal-code / country-name |
| 银行卡 | cc-name / cc-number / cc-exp / cc-csc |
| 登录注册 | username / current-password / new-password |
| 短信验证码 | one-time-code |
三个容易踩的点:第一,注册页写 current-password 会导致浏览器填错,注册和改密一律用 new-password;第二,同一页面有多组地址(收货 + 账单)时用 section- 前缀区分,比如 autocomplete="section-shipping address-line1";第三,中文场景别自造 autocomplete="address" 或 autocomplete="phone",浏览器只认标准 token。
验证码自动填充怎么做到 iOS 一键上屏?
结论:autocomplete="one-time-code" 配合 inputmode="numeric",再让短信内容带上可识别的验证码格式,iOS 键盘上方就会出现「来自短信」的填充建议。
<input type="text" inputmode="numeric" autocomplete="one-time-code"
name="code" maxlength="6" pattern="[0-9]*">
iOS 识别短信的推荐格式是「验证码是 123456」这类自然语句,或使用 @你的域名 #123456 的格式;页面必须走 HTTPS,凭据类自动填充在非安全上下文里会被限制。
常见组合坑有哪些?
结论:三个高频错误——用 type="number" 收手机号和卡号、用 autocomplete="off" 想禁掉填充、以为 inputmode 能替代校验。
正确的收尾做法是:语义字段(姓名、地址、卡号、密码、验证码)全部写上标准 autocomplete;键盘字段(数字、电话、邮箱)全部写上 inputmode;客户端和 Android/iOS 都只是「便利层」,金额范围、验证码长度、手机号格式仍需服务端复核。两行属性加起来不到 100 字节,能把移动端下单流程的输入步骤压掉一大半。
原文链接:https://www.gj0.com/thread-848.html
转载请注明出处并保留本声明;内容仅代表作者观点,与本站立场无关。若本文涉嫌侵权,请联系本站处理。