EditContext:textupdate 事件

可用性有限

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

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

当用户对已附加到 EditContext 实例的可编辑区域的文本或选区进行更改时,会触发 EditContext 接口的 textupdate 事件。

此事件使得能够响应用户输入,在 UI 中渲染更新后的文本和选区。

语法

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

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

ontextupdate = (event) => { }

事件类型

一个 TextUpdateEvent。继承自 Event

事件属性

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

TextUpdateEvent.updateRangeStart 只读

返回被更新的文本范围中的第一个字符的索引。

TextUpdateEvent.updateRangeEnd 只读

返回被更新的文本范围中的最后一个字符的索引。

TextUpdateEvent.text 只读

返回在更新范围中插入的文本。

TextUpdateEvent.selectionStart 只读

返回更新后,新选区范围中的第一个字符的索引。

TextUpdateEvent.selectionEnd 只读

返回更新后,新选区范围中的最后一个字符的索引。

示例

textupdate 上渲染更新后的文本

在以下示例中,EditContext API 的 textupdate 事件被用于渲染用户在可编辑的 <canvas> 元素中输入的文本。

html
<canvas id="editor-canvas"></canvas>
js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;

editContext.addEventListener("textupdate", (e) => {
  // When the user has focus on the <canvas> and enters text,
  // this event is fired, and we use it to re-render the text.
  console.log(
    `The user entered the text: ${e.text} at ${e.updateRangeStart}. Re-rendering the full EditContext text`,
  );
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText(editContext.text, 10, 10);
});

规范

规范
EditContext API
# dom-editcontext-ontextupdate

浏览器兼容性