← 中文资源

简体中文版本

inputMode 与 enterKeyHint 定制移动键盘

inputMode 选择移动端虚拟键盘布局,enterKeyHint 定义动作键文案,配合 autocapitalize 与 spellcheck,不改 input 类型也能优化移动表单体验。

阅读英文原文

实现说明

amountInput、nextField 定义在模块顶层,中间不经过函数作用域。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 演示输出是带标签的(moved on; enterKeyHint is),每个操作都会留下自己的一行标注。

常见问题

「inputMode 与 enterKeyHint 定制移动键盘」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

amountInput.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    event.preventDefault();
    nextField.focus();
    console.log('moved on; enterKeyHint is', amountInput.enterKeyHint);
  }
});

代码示例

const amountInput = document.querySelector('#amount') as HTMLInputElement;
const nextField = document.querySelector('#note') as HTMLInputElement;

// Numeric virtual keyboard with a decimal point, without number-input quirks.
amountInput.inputMode = 'decimal';
// Mobile keyboards label the action key "Next"; desktop browsers ignore it.
amountInput.enterKeyHint = 'next';
// Exact codes: no capitalization or correction help wanted.
amountInput.autocapitalize = 'off';
amountInput.spellcheck = false;

amountInput.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    event.preventDefault();
    nextField.focus();
    console.log('moved on; enterKeyHint is', amountInput.enterKeyHint);
  }
});