EditContext:textformatupdate 事件

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

当使用 输入法编辑器 (IME) 窗口进行文本输入时,会触发 EditContext 接口的 textformatupdate 事件。

当 IME 决定需要以不同方式格式化正在输入的文本的某些部分以指示输入状态时,会触发此事件。

下面的截图展示了一个在 Windows 的记事本应用中使用日文 IME 输入文本的示例。文本以粗下划线进行格式化,以表明它是从 IME 的建议之一中组成的。

Notepad on Windows with some Japanese text being composed from the IME window

作为 Web 开发者,您应该监听 textformatupdate 事件,并相应地更新可编辑区域中显示的文本格式。

语法

在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。

js
addEventListener("textformatupdate", (event) => { })

ontextformatupdate = (event) => { }

事件类型

一个 TextFormatUpdateEvent。继承自 Event

事件属性

除了下面列出的属性之外,父接口 Event 的属性也可使用。

TextFormatUpdateEvent.getTextFormats

返回 IME 窗口希望应用于该文本的文本格式列表。

示例

渲染 IME 输入文本的格式

在下面的示例中,textformatupdate 事件用于更新可编辑区域中文本的格式。请注意,此示例中的事件监听器回调仅在使用 IME 窗口或其他平台特定的编辑 UI 表面输入文本时调用。

html
<canvas id="editor-canvas"></canvas>
js
const TEXT_X = 10;
const TEXT_Y = 10;

const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");

const editContext = new EditContext();
canvas.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  // Clear the canvas.
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Render the text.
  ctx.fillText(editContext.text, TEXT_X, TEXT_Y);

  // Get the text formats that the IME window wants to apply.
  const formats = e.getTextFormats();

  // Iterate over the text formats
  for (const format of formats) {
    const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format;

    const underlineXStart = ctx.measureText(
      editContext.text.substring(0, rangeStart),
    ).width;
    const underlineXEnd = ctx.measureText(
      editContext.text.substring(0, rangeEnd),
    ).width;
    const underlineY = TEXT_Y + 3;

    // For brevity, this example only draws a simple underline.
    // You should use the underlineStyle and underlineThickness values to draw the underline.

    ctx.beginPath();
    ctx.moveTo(TEXT_X + underlineXStart, underlineY);
    ctx.lineTo(TEXT_X + underlineXEnd, underlineY);
    ctx.stroke();
  }
});

规范

规范
EditContext API
# dom-editcontext-ontextformatupdate

浏览器兼容性