compositionstart

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.

文本合成系统如 input method editor(即输入法编辑器)开始新的输入合成时会触发 compositionstart 事件。

例如,当用户使用拼音输入法开始输入汉字时,这个事件就会被触发。

Bubbles Yes
Cancelable Yes
Interface CompositionEvent
Event handler property
None

示例

js
const inputElement = document.querySelector('input[type="text"]');

inputElement.addEventListener("compositionstart", (event) => {
  console.log(`generated characters were: ${event.data}`);
});

动态演示

HTML

html
<div class="control">
  <label for="name"
    >On macOS, click in the textbox below,<br />
    then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label
  >
  <input type="text" id="example" name="example" />
</div>

<div class="event-log">
  <label>Event log:</label>
  <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea>
  <button class="clear-log">Clear</button>
</div>

JS

js
const inputElement = document.querySelector('input[type="text"]');
const log = document.querySelector(".event-log-contents");
const clearLog = document.querySelector(".clear-log");

clearLog.addEventListener("click", () => {
  log.textContent = "";
});

function handleEvent(event) {
  log.textContent = log.textContent + `${event.type}: ${event.data}\n`;
}

inputElement.addEventListener("compositionstart", handleEvent);
inputElement.addEventListener("compositionupdate", handleEvent);
inputElement.addEventListener("compositionend", handleEvent);

结果

规范

Specification
UI Events
# event-type-compositionstart

浏览器兼容性

BCD tables only load in the browser

参见