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 |
浏览器兼容性
加载中…