EditContext: characterboundsupdate 事件

可用性有限

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

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

当操作系统需要了解 EditContext 对象中可编辑文本区域内特定字符的边界时,会触发 characterboundsupdate 事件。

这发生在操作系统需要显示平台特定的与编辑相关的 UI 表面(例如 输入法编辑器 (IME) 窗口)时。

characterboundsupdate 事件触发时,您应该计算文本的字符边界,然后调用 EditContext.updateCharacterBounds() 方法,将操作系统所需的信息提供给它。

有关何时以及如何使用 characterboundsupdate 事件的更多信息,请参阅 updateCharacterBounds 方法的文档。

语法

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

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

oncharacterboundsupdate = (event) => { }

事件类型

一个 CharacterBoundsUpdateEvent。继承自 Event

事件属性

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

CharacterBoundsUpdateEvent.rangeStart 只读

操作系统需要边界的第一个字符在可编辑区域文本中的偏移量。

CharacterBoundsUpdateEvent.rangeEnd 只读

操作系统需要边界的最后一个字符在可编辑区域文本中的偏移量。

示例

在需要时更新字符边界

此示例展示了当操作系统指示需要信息时,如何使用 updateCharacterBounds 方法来更新 canvas 元素 EditContext 中的字符边界。请注意,事件监听器回调仅在使用 IME 窗口或其他平台特定的编辑 UI 表面来组合文本时被调用。

html
<canvas id="editor-canvas"></canvas>
js
const FONT_SIZE = 40;
const FONT = `${FONT_SIZE}px Arial`;

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

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

function computeCharacterBound(offset) {
  // Measure the width from the start of the text to the character.
  const widthBeforeChar = ctx.measureText(
    editContext.text.substring(0, offset),
  ).width;

  // Measure the character width.
  const charWidth = ctx.measureText(editContext.text[offset]).width;

  const charX = canvas.offsetLeft + widthBeforeChar;
  const charY = canvas.offsetTop;

  // Return a DOMRect representing the character bounds.
  return DOMRect.fromRect({
    x: charX,
    y: charY - FONT_SIZE,
    width: charWidth,
    height: FONT_SIZE,
  });
}

editContext.addEventListener("characterboundsupdate", (e) => {
  const charBounds = [];
  for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
    charBounds.push(computeCharacterBound(offset));
  }

  console.log("The required character bounds are", charBounds);
  editContext.updateCharacterBounds(e.rangeStart, charBounds);
});

规范

规范
EditContext API
# dom-editcontext-oncharacterboundsupdate

浏览器兼容性