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

文本合成系统如 {{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>

CSS

body {
  padding: .2rem;
  display: grid;
  grid-template-areas: "control  log";
}

.control {
  grid-area: control;
}

.event-log {
  grid-area: log;
}

.event-log-contents {
  resize: none;
}

label, button {
  display: block;
}

input[type="text"] {
  margin: .5rem 0;
}

kbd {
  border-radius: 3px;
  padding: 1px 2px 0;
  border: 1px solid black;
}

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

结果

规范

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

浏览器兼容性

{{Compat("api.Element.compositionstart_event")}}

参见