--- title: compositionstart slug: Web/API/Element/compositionstart_event tags: - Element - Event - Input method - compositionstart - 事件 - 参考 translation_of: Web/API/Element/compositionstart_event original_slug: Web/Events/compositionstart ---
{{APIRef}}

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

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

Bubbles Yes
Cancelable Yes
Interface {{domxref("CompositionEvent")}}
Event handler property
None

示例

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

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

动态演示

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

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);

结果

{{ EmbedLiveSample('Live_example', '100%', '180px') }}

规范

规范 状态
{{SpecName('UI Events', '#event-type-compositionstart')}} {{Spec2('UI Events')}}

浏览器兼容性

{{Compat}}

参见