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

瀏覽器相容性