EditContext: updateSelection() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

EditContext 介面的 updateSelection() 方法會更新可編輯文字上下文中選區(selection)的內部狀態。當用戶透過點選或拖動滑鼠,或使用鍵盤等方式與 EditContext 的關聯元素中的文字渲染進行互動時,就會使用此方法來更新選區狀態。

語法

js
updateSelection(start, end)

引數

start

一個代表新選區起始位置的數字。

end

一個代表新選區結束位置的數字。如果 startend 的值相同,則該選區等同於一個插入符號(caret)。

返回值

無 (undefined)。

異常

TypeError

如果呼叫方法時提供的引數少於兩個,或者任一引數不是非負數,則會丟擲此錯誤。

示例

使用者與文字互動時更新選區

此示例展示瞭如何在使用者使用箭頭鍵在可編輯區域移動插入符號或選擇文字時,使用 updateSelection 方法更新 canvas 元素的 EditContext 中的選區。

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

canvas.addEventListener("keydown", (e) => {
  if (e.key === "ArrowLeft") {
    const newPosition = Math.max(editContext.selectionStart - 1, 0);

    if (e.shiftKey) {
      editContext.updateSelection(newPosition, editContext.selectionEnd);
    } else {
      editContext.updateSelection(newPosition, newPosition);
    }
  } else if (e.key === "ArrowRight") {
    const newPosition = Math.min(
      editContext.selectionEnd + 1,
      editContext.text.length,
    );

    if (e.shiftKey) {
      editContext.updateSelection(editContext.selectionStart, newPosition);
    } else {
      editContext.updateSelection(newPosition, newPosition);
    }
  }

  console.log(
    `The new EditContext selection is ${editContext.selectionStart}, ${editContext.selectionEnd}`,
  );
});

規範

規範
EditContext API
# dom-editcontext-updateselection

瀏覽器相容性

另見