关于输入法事件的切换监听

JS判断当前文本的输入法<输入状态>
更新于: 2023-04-27 14:54:25
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="control">
      <label for="example">
        First select textbox, then to open IME:
        <ul>
          <li>on macOS type <kbd>option</kbd> + <kbd>`</kbd></li>
          <li>on Windows type <kbd>windows</kbd> + <kbd>.</kbd></li>
        </ul>
      </label>
      <input type="text" id="example" name="example" />
    </div>

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

    <script>
      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 += `${event.type}: ${event.data}\n`;
      }

      inputElement.addEventListener('compositionstart', handleEvent);
      inputElement.addEventListener('compositionupdate', handleEvent);
      inputElement.addEventListener('compositionend', handleEvent);
    </script>
  </body>
</html>