在 IME 组合期间将光标移动到其他文本框

问题描述

我想在用户输入时使用 javascript 将光标移动到另一个文本输入字段。当组成部首(韩文、日文、中文)时,它会导致意想不到的行为。

例如如果用户在第一个文本框中键入 ,则光标应移动到第二个文本框中。但是,当继续在第二个文本框中键入时,第一个文本框中的 仍然是持久的。

[|   ]  [    ]      cursor in first Box
[나   ]  [|   ]      typed 나 and cursor move
[나   ]  [난|  ]      typed ㄴ

仅键入 ㄴ+ㅏ+ㄴ生成字符 나,난 而不是 나,ㄴ

const a = document.getElementById("a");
const b =  document.getElementById("b");
a.oninput = e => { if (a.value == '나') b.focus(); };
<input type="text" id="a">
<input type="text" id="b">

我想在 Windows 和 MacOS 上支持 Chrome、Safari、Firefox、Opera、Edge。


更广泛的日志。

const a = document.getElementById("a");
const b =  document.getElementById("b");
const c =  document.getElementById("c");

[a,b].forEach(el => {
  let log = e => c.textContent += `${el.id} ${event.type}: ${event.data}\n`;

  el.addEventListener("blur",log);
  el.addEventListener("keydown",log);
  el.addEventListener("compositionstart",log);
  el.addEventListener("compositionupdate",log);
  el.addEventListener("compositionend",log);
  el.addEventListener("input",log);
});

a.addEventListener("input",e => {
  if (a.value == '나') b.focus();
});
<input type="text" id="a">
<input type="text" id="b">
<br><pre type="text" id="c"></pre>

输出

a keydown: undefined
a compositionstart: 
a compositionupdate: ㄴ
a input: ㄴ
a keydown: undefined
a compositionupdate: 나
a input: 나
a compositionend: 나
a blur: undefined
b keydown: undefined
b compositionstart: 
b compositionupdate: 난
b input: 난
// on clicking somewhere else => blurring the b field
b compositionend: 난
b blur: undefined

解决方法

嗯,这样做很容易。您只需要在 i 上调用 blur

a
const a = document.getElementById("a");
const b =  document.getElementById("b");
a.oninput = e => { if (a.value == '나') { b.focus();a.blur(); } };

,

我使用 Jquery 生成跨浏览器解决方案。告诉我它运作良好,伙计!

<input type="text" id="a">
<input type="text" id="b">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>
const a = document.getElementById("a");
const b =  $("#b");
a.oninput = e => { if (a.value == 'c') b.trigger('focus'); };
</script>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...